//
//  DeleteAccountVC.swift
//  WoWonder
//
//  Created by My Mac on 09/05/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import UIKit
import WowonderMessengerSDK
import Async
import CoreData
import Toast_Swift

class DeleteAccountVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet var headerView: UIView!
    @IBOutlet var passwordTextField: UITextField!
    @IBOutlet var passwordTextFieldView: UIView!
    @IBOutlet var checkBoxButton: UIButton!
    @IBOutlet var descriptionLabel: UILabel!
    
    // MARK: - Properties
    
    var isTerms = false
    let socketHelper = SocketHelper.shared
    
    // MARK: - View Life Cycles
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initialConfig()
    }
    
    // MARK: - Selectors
    
    // Back Button Action
    @IBAction func backButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.navigationController?.popViewController(animated: true)
    }
    
    // Check Box Button Action
    @IBAction func checkBoxButtonAction(_ sender: UIButton) {
        self.isTerms = !self.isTerms
        if self.isTerms {
            self.checkBoxButton.setImage(UIImage(named: "checkboxfill"), for: .normal)
        } else {
            self.checkBoxButton.setImage(UIImage(named: "checkbox"), for: .normal)
        }
    }
    
    // Delete Account Button Action
    @IBAction func deleteAccountButtonAction(_ sender: UIButton) {
        if !self.isTerms {
            if let alertVC = R.storyboard.popup.warningAlertVC() {
                alertVC.titleText  = "Warning !"
                alertVC.messageText = "You can not access your disapproval of the Terms and Conditions"
                alertVC.okText = "OK"
                self.present(alertVC, animated: true, completion: nil)
                alertVC.cancelButton.isHidden = true
            }
            return
        }
        if passwordTextField.text?.trimmingCharacters(in: .whitespaces).count == 0 {
            if let alertVC = R.storyboard.popup.warningAlertVC() {
                alertVC.titleText  = "Warning !"
                alertVC.messageText = "Error, Please confirm your password"
                alertVC.okText = "OK"
                self.present(alertVC, animated: true, completion: nil)
                alertVC.cancelButton.isHidden = true
            }
            return
        }
        self.deleteAccount()
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.textFieldSetUp()
        self.setData()
    }
    
    func textFieldSetUp() {
        self.passwordTextField.attributedPlaceholder = NSAttributedString(
            string: "Password",
            attributes: [NSAttributedString.Key.foregroundColor: UIColor.text_color_in_between as Any]
        )
        self.passwordTextField.delegate = self
    }
    
    // Set Data
    func setData() {
        self.descriptionLabel.text = "Yes, I want to delete \(AppInstance.instance.userProfile?.username ?? "") permanently from WoWonder Messenger Account."
    }
    
    @objc func update() {
        UserDefaults.standard.removeValuefromUserdefault(Key: Local.USER_SESSION.User_Session)
        UserDefaults.standard.clearUserDefaults()
        self.socketHelper.disconnect()
        let entities = appDelegate.persistentContainer.managedObjectModel.entities
        for entity in entities {
            delete(entityName: entity.name!)
        }
        self.dismiss(animated: true) {
            let newVC = R.storyboard.main.signUpMainNav()
            appDelegate.window?.rootViewController = newVC
        }
    }
    
    func delete(entityName: String) {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try appDelegate.persistentContainer.viewContext.execute(deleteRequest)
        } catch let error as NSError {
            debugPrint(error)
        }
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension DeleteAccountVC {
    
    private func deleteAccount() {
        if Connectivity.isConnectedToNetwork() {
            let sessionToken = AppInstance.instance.sessionId ?? ""
            Async.background {
                UserManager.instance.deleteUser(sessionToken: sessionToken, password: self.passwordTextField.text ?? "", completionBlock: { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("Success = \(success?.message ?? "")")
                                self.update()
                                self.navigationController?.popViewController(animated: true)
                                let newVC = R.storyboard.main.signUpMainNav()
                                appDelegate.window?.rootViewController = newVC
                            }
                        }
                    } else if sessionError != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                print("session Error = \(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: UITextFieldDelegate Methods
extension DeleteAccountVC: UITextFieldDelegate {
    
    func textFieldDidBeginEditing(_ textField: UITextField) {
        switch textField {
        case passwordTextField:
            self.passwordTextFieldView.borderColorV = .accent
        default:
            break
        }
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        switch textField {
        case passwordTextField:
            self.passwordTextFieldView.borderColorV = .color_divider
        default:
            break
        }
    }
    
}
