//
//  BroadcastVC.swift
//  WoWonder
//
//  Created by iMac on 16/05/24.
//  Copyright © 2024 ScriptSun. All rights reserved.
//

import UIKit
import Async
import SDWebImage

class BroadcastVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var emptyView: UIView!
    
    // MARK: - Properties
    
    var broadcastArray: [BroadcastData] = []
    var broadcastList: [Broadcast] = []
    
    // MARK: - View Life Cycles

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        self.getBroadcastlist()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Add Button Action
    @IBAction func addButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.broadcast.createBroadcastVC() {
            newVC.delegate = self
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.tableViewSetup()
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(UINib(resource: R.nib.broadcastCell), forCellReuseIdentifier: R.reuseIdentifier.broadcastCell.identifier)
        self.tableView.refreshControl = UIRefreshControl()
        self.tableView.refreshControl?.addTarget(self, action: #selector(self.refreshBroadcast), for: .valueChanged)
    }
    
    // Refresh Broadcast
    @objc func refreshBroadcast() {
        self.broadcastList = []
        self.getBroadcastlist()
    }
    
    // Get Broadcast List
    func getBroadcastlist() {
        let appDelegate = (UIApplication.shared.delegate) as? AppDelegate
        let context = appDelegate?.persistentContainer.viewContext
        let broadcasts = Broadcast.getBroadcast()
        if !broadcasts.isEmpty {
            self.broadcastList = broadcasts
            self.tableView.reloadData()
            if self.broadcastList.count == 0 {
                self.emptyView.isHidden = false
            } else {
                self.emptyView.isHidden = true
            }
            self.getBroadcastApi { [weak self] response in
                guard let self = self else { return }
                guard let list = response.data else {
                    self.tableView.reloadData()
                    return
                }
                for broadcast in list {
                    if let broadcastChat = Broadcast.getBroadcastById(broadcast.id ?? 0) {
                        broadcastChat.updateBroadcast(broadcast)
                    } else {
                        let localBroadcast = Broadcast(broadcast: broadcast)
                        localBroadcast.save()
                    }
                }
                for broadcast in Broadcast.getBroadcast() {
                    if !list.contains(where: { broadcastData in
                        (broadcastData.id ?? 0) == Int(broadcast.broadcast_id)
                    }) {
                        context?.delete(broadcast)
                        do {
                            try context?.save()
                        } catch {
                            print("failed so save data after deleting object")
                        }
                    }
                }
                self.broadcastList = Broadcast.getBroadcast()
                self.tableView.refreshControl?.endRefreshing()
                self.tableView.reloadData()
                if self.broadcastList.count == 0 {
                    self.emptyView.isHidden = false
                } else {
                    self.emptyView.isHidden = true
                }
            }
        } else {
            self.broadcastList = []
            self.getBroadcastApi { model in
                Async.main {
                    self.dismissProgressDialog {
                        guard let data = model.data else {
                            self.tableView.reloadData()
                            return
                        }
                        for broadcast in data {
                            if let broadcastChat = Broadcast.getBroadcastById(broadcast.id ?? 0) {
                                self.broadcastList.append(broadcastChat)
                            } else {
                                let localBroadcast = Broadcast(broadcast: broadcast)
                                localBroadcast.save()
                                self.broadcastList.append(localBroadcast)
                            }
                        }
                        self.tableView.reloadData()
                        self.tableView.refreshControl?.endRefreshing()
                        if self.broadcastList.count == 0 {
                            self.emptyView.isHidden = false
                        } else {
                            self.emptyView.isHidden = true
                        }
                    }
                }
            }
        }
    }

}

// MARK: - Extensions

// MARK: Api Call
extension BroadcastVC {
    
    func getBroadcastApi(_ completion: @escaping (BroadcastModel) -> Void) {
        let sessionToken = AppInstance.instance.sessionId ?? ""
        Async.background {
            BroadcastManager.instance.getBroadcast(session_Token: sessionToken, limit: 0, offset: 0, completionBlock: { (success, sessionError, serverError, error) in
                if success != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            print("Broadcast List = \(success?.data ?? [])")
                            self.broadcastArray = success?.data ?? []
                            guard let success = success else { return }
                            completion(success)
                        }
                    }
                } else if sessionError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(sessionError?.errors?.error_text ?? "")
                            print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                        }
                    }
                } else if serverError != nil {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(serverError?.errors?.error_text)
                            print("serverError = \(serverError?.errors?.error_text ?? "")")
                        }
                    }
                } else {
                    Async.main {
                        self.dismissProgressDialog {
                            self.view.makeToast(error?.localizedDescription)
                            print("error = \(error?.localizedDescription ?? "")")
                        }
                    }
                }
            })
        }
    }
    
}

// MARK: TableView Setup
extension BroadcastVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.broadcastList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.broadcastCell.identifier) as! BroadcastCell
        if self.broadcastList.count != 0 {
            self.setBroadcastData(cell: cell, indexPath: indexPath)
        }
        return cell
    }
    
    // Set Broadcast Data
    func setBroadcastData(cell: BroadcastCell, indexPath: IndexPath) {
        if self.broadcastList.isEmpty {
            cell.showAnimation()
        }
        cell.hideAnimation()
        let objectBroadcast = self.broadcastList[indexPath.row]
        let url = URL(string: objectBroadcast.image ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        cell.broadcastImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            cell.broadcastImageView.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
        cell.broadcastNameLabel.text = objectBroadcast.name
        cell.broadcastDescriptionLabel.text = "Broadcast list - \(objectBroadcast.getUsers().count) recipients"
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        self.tableView.deselectRow(at: indexPath, animated: true)
        let objectBroadcast = self.broadcastList[indexPath.row]
        if let newVC = R.storyboard.broadcast.broadcastChatVC() {
            newVC.broadcast = objectBroadcast
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
}

// MARK: CreateBroadcastVCDelegate
extension BroadcastVC: CreateBroadcastVCDelegate {
    
    func handleCreateBroadcast(broadcast: Broadcast?) {
        if let newVC = R.storyboard.broadcast.broadcastChatVC() {
            newVC.broadcast = broadcast
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
}
