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

import UIKit
import SDWebImage
import CoreData
import Async
import WowonderMessengerSDK
import Toast_Swift

class EditBroadcastVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var broadcastImage: UIImageView!
    @IBOutlet weak var cameraImage: UIImageView!
    @IBOutlet weak var broadcastNameTextField: EmojiTextField!
    @IBOutlet weak var broadcastNameBorderView: UIView!
    @IBOutlet weak var keyboardTypeButton: UIButton!
    @IBOutlet weak var viewTableView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var saveButton: UIButton!
    @IBOutlet weak var deleteBroadcastButton: UIButton!
    
    // MARK: - Properties
    
    private var selectedUsersArray: [UserData] = []
    private var newAddedUserIds = ""
    private var oldUserRemovedIds = ""
    private let imagePickerController = UIImagePickerController()
    private var imageData: Data? = nil
    var broadcastData: BroadcastData?
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        if self.selectedUsersArray.count == 0 {
            self.viewTableView.isHidden = true
        } else {
            self.viewTableView.isHidden = false
            self.tableViewHeightConstraint.constant = CGFloat(68 * self.selectedUsersArray.count)
        }
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Keyboard Type Button Action
    @IBAction func keyboardTypeButtonAction(_ sender: UIButton) {
        self.broadcastNameTextField.isEmojiKeyboard = !(self.broadcastNameTextField.isEmojiKeyboard)
        self.broadcastNameTextField.becomeFirstResponder()
        self.broadcastNameTextField.reloadInputViews()
        self.keyboardTypeButton.setImage(self.broadcastNameTextField.isEmojiKeyboard ? R.image.icon_keyboard_vector() : R.image.icon_emoji_vector(), for: .normal)
    }
    
    // Add Image Button Action
    @IBAction func addImageButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        let alert = UIAlertController(title: "Select Source", message: "", preferredStyle: .alert)
        let camera = UIAlertAction(title: "Camera", style: .default) { action in
            if !UIImagePickerController.isSourceTypeAvailable(.camera) {
                self.view.makeToast("camera not found...")
                return
            }
            self.imagePickerController.sourceType = .camera
            self.present(self.imagePickerController, animated: true, completion: nil)
        }
        let gallery = UIAlertAction(title: "Gallery", style: .default) { (action) in
            self.imagePickerController.sourceType = .photoLibrary
            self.present(self.imagePickerController, animated: true, completion: nil)
        }
        let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: nil)
        alert.addAction(camera)
        alert.addAction(gallery)
        alert.addAction(cancel)
        self.present(alert, animated: true, completion: nil)
    }
    
    // Add Recipients Button Action
    @IBAction func addRecipientsButtonAction(_ sender: UIButton) {
        if let newVC = R.storyboard.group.addParticipantsListViewController() {
            newVC.delegate = self
            newVC.selectedUserArray = self.selectedUsersArray
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Save Button Action
    @IBAction func saveButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.saveNewUserAdd()
    }
    
    // Delete Broadcast Button Action
    @IBAction func deleteBroadcastButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let alertVC = R.storyboard.group.groupAlertVC() {
            alertVC.delegate = self
            alertVC.messageText = "Are you sure you want to delete the broadcast"
            alertVC.okText = "DELETE BROADCAST"
            self.present(alertVC, animated: true, completion: nil)
            alertVC.okButton.tag = 3003
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.imagePickerController.delegate = self
        self.imagePickerController.allowsEditing = false
        self.tableViewSetup()
        self.textFieldSetup()
        self.setData()
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.register(UINib(resource: R.nib.groupAddParticipantsCell), forCellReuseIdentifier: R.reuseIdentifier.groupAddParticipantsCell.identifier)
    }
    
    // TextField Setup
    func textFieldSetup() {
        self.broadcastNameTextField.attributedPlaceholder = NSAttributedString(
            string: "Enter name broadcast",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.broadcastNameTextField.delegate = self
    }
    
    private func setData() {
        self.broadcastNameTextField.text = self.broadcastData?.name ?? ""
        let url = URL(string: self.broadcastData?.image ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        self.broadcastImage.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            self.broadcastImage.sd_setImage(with: url, placeholderImage: UIImage(named: "")) { image, error, cache, url in
                if image != nil {
                    if self.broadcastImage.image != nil {
                        self.imageData = self.broadcastImage.image?.jpegData(compressionQuality: 1)
                        self.cameraImage.isHidden = true
                    }
                }
            }
        }
        self.selectedUsersArray = self.broadcastData?.users ?? []
        self.tableView.reloadData()
        if self.selectedUsersArray.count == 0 {
            self.viewTableView.isHidden = true
        } else {
            self.tableViewHeightConstraint.constant = CGFloat(68 * self.selectedUsersArray.count)
        }
    }
    
    func saveNewUserAdd() {
        self.newAddedUserIds = self.selectedUsersArray.filter({ user1 in
            let result = self.broadcastData?.users?.contains { user2 in
                user1.user_id == user2.user_id
            }
            return !(result ?? false)
        }).map { userData in
            return userData.user_id ?? ""
        }.joined(separator: ", ")
        print("newAddedUserIds >>>>>", self.newAddedUserIds)
        
        self.oldUserRemovedIds = self.broadcastData?.users?.filter({ user1 in
            let result = self.selectedUsersArray.contains { user2 in
                user1.user_id == user2.user_id
            }
            return !(result)
        }).map { userData in
            return userData.user_id ?? ""
        }.joined(separator: ", ") ?? ""        
        print("oldUserRemovedIds >>>>>", self.oldUserRemovedIds)
        
        if self.imageData == nil {
            self.view.makeToast("Please select broadcast avatar")
            return
        }
        if self.broadcastNameTextField.text?.trimmingCharacters(in: .whitespaces).count == 0 {
            self.view.makeToast("Please enter broadcast name")
            return
        }
        if self.selectedUsersArray.count < 2 {
            self.view.makeToast("Please select at least two users")
            return
        }
        self.editBroadcast()
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension EditBroadcastVC {
    
    // Delete Broadcast
    private func deleteBroadcast() {
        if Connectivity.isConnectedToNetwork() {
            let sessionToken = AppInstance.instance.sessionId ?? ""
            let broadcast_id = self.broadcastData?.id ?? 0
            Async.background {
                BroadcastManager.instance.deleteBroadcast(broadcast_id: broadcast_id, session_Token: sessionToken, completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("success = \(success?.api_status ?? 0)")
                                guard let broadcast_id = self.broadcastData?.id else { return }
                                let appDelegate = (UIApplication.shared.delegate) as? AppDelegate
                                let context = appDelegate?.persistentContainer.viewContext
                                let predicate = NSPredicate(format: "%K == %d", #keyPath(Broadcast.broadcast_id), broadcast_id)
                                let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Broadcast")
                                fetchRequest.predicate = predicate
                                let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
                                do {
                                    try context?.execute(deleteRequest)
                                    try context?.save()
                                } catch {
                                    print("error >>>>> ", error.localizedDescription)
                                }
                                if let viewControllers = self.navigationController?.viewControllers {
                                    for viewController in viewControllers {
                                        if viewController is BroadcastVC {
                                            self.navigationController?.popToViewController(viewController, animated: true)
                                            break
                                        }
                                        if viewController is GroupVC {
                                            self.navigationController?.popToViewController(viewController, animated: true)
                                            break
                                        }
                                    }
                                }
                                appDelegate?.window?.rootViewController?.view.makeToast(success?.message)
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                                self.view.makeToast(sessionError?.errors?.error_text ?? "")
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                                self.view.makeToast(serverError?.errors?.error_text ?? "")
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                print("error = \(error?.localizedDescription ?? "")")
                                self.view.makeToast(error?.localizedDescription ?? "")
                            }
                        }
                    }
                })
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
    // Edit Broadcast
    private func editBroadcast() {
        if Connectivity.isConnectedToNetwork() {
            let sessionToken = AppInstance.instance.sessionId ?? ""
            let broadcast_name  = self.broadcastNameTextField.text ?? ""
            let imageData = self.imageData ?? Data()
            let broadcast_id = self.broadcastData?.id ?? 0
            Async.background {
                BroadcastManager.instance.editBroadcasr(session_Token: sessionToken, name: broadcast_name, broadcast_id: broadcast_id, added_users: self.newAddedUserIds, remove_users: self.oldUserRemovedIds, avatar_data: imageData, completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("success = \(success?.api_status ?? 0)")
                                self.navigationController?.popViewController(animated: true)
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("sessionError = \(sessionError?.errors?.error_text ?? "")")
                                self.view.makeToast(sessionError?.errors?.error_text ?? "")
                            }
                        }
                    } else if serverError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("serverError = \(serverError?.errors?.error_text ?? "")")
                                self.view.makeToast(serverError?.errors?.error_text ?? "")
                            }
                        }
                    } else {
                        Async.main {
                            self.dismissProgressDialog {
                                print("error = \(error?.localizedDescription ?? "")")
                                self.view.makeToast(error?.localizedDescription ?? "")
                            }
                        }
                    }
                })
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
}

// MARK: TableView Setup
extension EditBroadcastVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return selectedUsersArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "GroupAddParticipantsCell", for: indexPath) as! GroupAddParticipantsCell
        let userData = self.selectedUsersArray[indexPath.row]
        cell.delegate = self
        cell.indexPath = indexPath
        cell.cancelButton.isHidden = "\(self.broadcastData?.user_id ?? 0)" == userData.user_id
        cell.setData(object: userData)
        return cell
    }
    
}

//MARK: AddParticipantsListViewControllerDelegate Methods
extension EditBroadcastVC: AddParticipantsListViewControllerDelegate {
    
    func sendSelectedParticipants(selectedParticipants: [UserData]) {
        self.selectedUsersArray = selectedParticipants
        self.tableView.reloadData()
        if self.selectedUsersArray.count == 0 {
            self.viewTableView.isHidden = true
        } else {
            self.tableViewHeightConstraint.constant = CGFloat(68 * self.selectedUsersArray.count)
        }
    }
    
}

// MARK: UIImagePickerControllerDelegate Methods
extension EditBroadcastVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        let image = info[UIImagePickerController.InfoKey.originalImage] as! UIImage
        self.broadcastImage.image = image
        self.cameraImage.isHidden = true
        self.imageData = image.jpegData(compressionQuality: 1)
        self.dismiss(animated: true, completion: nil)
    }
    
}

// MARK: deleteParticipantDelegate Methods
extension EditBroadcastVC: GroupAddParticipantsCellDelegate {
    
    func handleDeleteParticipant(indexPath: IndexPath) {
        if let alertVC = R.storyboard.group.groupAlertVC() {
            alertVC.delegate = self
            alertVC.messageText = "Remove " + (self.selectedUsersArray[indexPath.row].name ?? "")
            alertVC.okText = "YES"
            alertVC.cancelText = "NO"
            self.present(alertVC, animated: true, completion: nil)
            alertVC.okButton.tag = indexPath.row
        }
    }
    
}

// MARK: GroupAlertVCDelegate Methods
extension EditBroadcastVC: GroupAlertVCDelegate {
    
    func groupAlertOKButtonPressed(_ sender: UIButton) {
        if sender.tag == 3003 {
            self.deleteBroadcast()
        } else {
            self.selectedUsersArray.remove(at: sender.tag)
            self.tableView.reloadData()
            if self.selectedUsersArray.count == 0 {
                self.viewTableView.isHidden = true
            } else {
                self.tableViewHeightConstraint.constant = CGFloat(68 * self.selectedUsersArray.count)
            }
        }
    }
    
}

// MARK: UITextFieldDelegate Methods
extension EditBroadcastVC: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case self.broadcastNameTextField:
            self.broadcastNameBorderView.backgroundColor = .accent
        default:
            break
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case self.broadcastNameTextField:
            self.broadcastNameBorderView.backgroundColor = UIColor(hex: "DDDDDD")
            self.broadcastNameTextField.isEmojiKeyboard = false
            self.keyboardTypeButton.setImage(self.broadcastNameTextField.isEmojiKeyboard ? R.image.icon_keyboard_vector() : R.image.icon_emoji_vector(), for: .normal)
        default:
            break
        }
    }
    
}
