//
//  GroupInfoViewController.swift
//  WoWonder
//
//  Created by UnikApp on 02/12/22.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import UIKit
import Async
import Toast_Swift
import WowonderMessengerSDK
import SDWebImage

class GroupInfoViewController: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var groupImage: UIImageView!
    @IBOutlet weak var groupNameLabel: UILabel!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!
    @IBOutlet weak var exitGroupButton: UIButton!
    
    // MARK: - Properties
    
    var groupData: GroupData?
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Exit Group Button Action
    @IBAction func exitGroupButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let alertVC = R.storyboard.group.groupAlertVC() {
            alertVC.delegate = self
            alertVC.messageText = "Are you sure to exit the group"
            alertVC.okText = "EXIT"
            self.present(alertVC, animated: true, completion: nil)
        }
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.tableViewSetup()
        self.setData()
    }
    
    // Set Data
    func setData() {
        self.groupNameLabel.text = self.groupData?.group_name ?? ""
        let url = URL(string: self.groupData?.avatar ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        self.groupImage.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            self.groupImage.sd_setImage(with: url, placeholderImage: UIImage(named: ""))
        }
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.register(UINib(resource: R.nib.groupAddParticipantsCell), forCellReuseIdentifier: R.reuseIdentifier.groupAddParticipantsCell.identifier)
        self.tableViewHeightConstraint.constant = CGFloat(68 * (self.groupData?.parts?.count ?? 0))
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension GroupInfoViewController {
    
    private func exitGroup() {
        if Connectivity.isConnectedToNetwork() {
            let sessionToken = AppInstance.instance.sessionId ?? ""
            let group_id = self.groupData?.group_id ?? ""
            Async.background {
                GroupChatManager.instance.leaveGroup(group_Id: group_id, session_Token: sessionToken, type: "leave", completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("success = \(success?.api_status ?? 0)")
                                self.navigationController?.popViewController(animated: true)
                                appDelegate.window?.rootViewController?.view.makeToast(success?.message_data)
                            }
                        }
                    } 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 GroupInfoViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.groupData?.parts?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.groupAddParticipantsCell.identifier, for: indexPath) as! GroupAddParticipantsCell
        if let userData = self.groupData?.parts?[indexPath.row] {
            cell.cancelButton.isHidden = true
            cell.setData(object: userData)
        }
        return cell
    }
    
}

// MARK: GroupAlertVCDelegate Methods
extension GroupInfoViewController: GroupAlertVCDelegate {
    
    func groupAlertOKButtonPressed(_ sender: UIButton) {
        self.exitGroup()
    }
    
}
