//
//  SideMenuVM.swift
//  WOKA
//
//  Created by MacBook Pro on 21/05/24.
//

import UIKit
import Alamofire

class SideMenuVM{
    
    weak var vc : SideMenuVC!
    
    func initView(){
        
        /*
         its put in ver 25.1.7 build 7 for testing purpose
         */
        vc.appVersion.addTapGesture {
            fatalError()
        }
        
        AuthFunc.shareInstance.getDefaultLanguage() == .english ? (vc.languageControl.selectedSegmentIndex = 0) :  (vc.languageControl.selectedSegmentIndex = 1)
        vc.appVersion.text = "VER: \(Bundle.main.appVersionLong) (\(Bundle.main.appBuild))"
        customizeSegmentControl()
        let color1 = #colorLiteral(red: 0.144693464, green: 0.1426281333, blue: 0.6686832905, alpha: 1)
        let color2 = #colorLiteral(red: 0.6901960784, green: 0.2745098039, blue: 0.7568627451, alpha: 1)
        
        vc.logoutBtn.applyGradient(colors: [color1, color2], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0, y: 0.8))
        vc.logoutBtn.layer.cornerRadius = vc.logoutBtn.frame.height / 2
        
        // Adding the trailing constriant to make the view appeared center when expanded
        let sidemenuBasicConfiguration = SideMenuController.preferences.basic
        let showPlaceTableOnLeft = (sidemenuBasicConfiguration.position == .under) != (sidemenuBasicConfiguration.direction == .right)
        if showPlaceTableOnLeft {
            vc.selectionMenuTrailingConstraint.constant = SideMenuController.preferences.basic.menuWidth - vc.view.frame.width
        }
        
        // Add border to theme
        
        vc.theme1.addBorderView(width: 1.5, color: UIColor.white)
        vc.theme2.addBorderView(width: 1.5, color: UIColor.white)
        
        vc.theme1.addTapGesture { [weak self] in
            PersistentStorage.shared.addOthersCount()

            guard let self else {return}

            if AuthFunc.shareInstance.selectedTheme == .theme1{
                return
            }

            UserDefaults.standard.setValue(ThemeSelect.theme1.rawValue, forKey: K.UserDefaultsStruct.themeDefault)
            AuthFunc.shareInstance.selectedTheme = .theme1
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.success)
            ViewButtonAnimation.sharedInstance.btnTapped(in: self.vc, view: vc.theme1) {

                NotificationCenter.default.post(name: NSNotification.Name(K.NotificationCenterReloads.reloadTheme), object: nil, userInfo: nil)
                self.themeSelect()
            }
        }
        
        vc.theme2.addTapGesture { [weak self] in
            PersistentStorage.shared.addOthersCount()

            guard let self else {return}

            if AuthFunc.shareInstance.selectedTheme == .theme2{
                return
            }
            
            UserDefaults.standard.setValue(ThemeSelect.theme2.rawValue, forKey: K.UserDefaultsStruct.themeDefault)
            AuthFunc.shareInstance.selectedTheme = .theme2
            let generator = UINotificationFeedbackGenerator()
            generator.notificationOccurred(.success)
            ViewButtonAnimation.sharedInstance.btnTapped(in: self.vc, view: vc.theme2) {
                NotificationCenter.default.post(name: NSNotification.Name(K.NotificationCenterReloads.reloadTheme), object: nil, userInfo: nil)
                self.themeSelect()
            }
        }
        
        
        setData()
    }
    
    func setData(){
        guard let data = AuthFunc.shareInstance.userData else{return}
        
        /*
         Check User Type,
         Dont show username if the user type is guest
         */
        switch data.userType{
        case "1": // child
            vc.addChildBtn.isHidden = true
            vc.userName.text = (data.fullname == nil || data.fullname == "") ? "User" : data.fullname
        case "2" : // adult
            vc.addChildBtn.isHidden = false
            vc.userName.text = (data.fullname == nil || data.fullname == "") ? "User" : data.fullname
        case "3": // Guest
            vc.userName.text = ""
            vc.profileBtn.isHidden = true
            vc.addChildBtn.isHidden = true
            vc.deactivateBtn.isHidden = true
            vc.myOrderBtn.isHidden = true
            vc.logoutBtn.setTitle("Login/Register", for: .normal)
            break
        default:
            break
        }
        
        if let avatar = data.avtarURL{
//            vc.avatarImage.imageURL("https://wokaland.com/secret-panel-10102023/hidden-admin-portal-20092023/storage/app/public/uploads/avtar/avatar2.png?d=1716889852")
            vc.avatarImage.imageURL(avatar)
        }else{
            vc.avatarImage.image = UIImage(named: "DefaultAvatar")
        }
    }
    
    func themeSelect(){
        switch AuthFunc.shareInstance.selectedTheme {
        case .theme1:
            //Show theme 1 selected
            vc.themeOneView.isHidden = false
            vc.themeOneCheckMark.isHidden = false
            
            // remove theme 2 selection
            vc.themeTwoView.isHidden = true
            vc.themetwoCheckMark.isHidden = true
        case .theme2:
            //Show theme 2 selected
            vc.themeTwoView.isHidden = false
            vc.themetwoCheckMark.isHidden = false
            
            // remove theme 1 selection
            vc.themeOneView.isHidden = true
            vc.themeOneCheckMark.isHidden = true
        }
        self.vc.sideMenuController?.hideMenu()
    }
    
    private func customizeSegmentControl(){
        // Customize Segment Control
        vc.languageControl.layer.cornerRadius = vc.languageControl.layer.frame.height / 2
        vc.languageControl.layer.masksToBounds = true
        vc.languageControl.clipsToBounds = true
    }
    
    // MARK: - Get Intrests
    
    func logoutUser(onCompletion: @escaping (Bool) -> Void){

        let headers : HTTPHeaders = ["Accept-Language" : AuthFunc.shareInstance.languageSelected == .english ? "English" : "Hindi",
                                     "access-token": AuthFunc.shareInstance.getAccessToken()]
        
        Utilities.startProgressHUD()
        NetworkManager.shareInstance.apiRequest(url: APIEndPoints.SideBarNav.user_logout, method: .post, headers: headers) {(result : Result<BaseResponseModel<IntrestTopicDM>, NetworkManager.APIError>) in
            switch result{
            case .success(let data):
                //0 -> Username already used. , 1-> Username available
                switch data.success{
                case 0:
                    Utilities.dismissProgressHUD()
                    self.vc.toast(msg: data.message ?? "Unrecognised error" , time: 2)
                    onCompletion(false)
                case 1:
                    Utilities.dismissProgressHUD()
                    onCompletion(true)
                default:
                    break
                }
            case .failure(let error):
                Utilities.dismissProgressHUD()
                self.vc.toast(msg: error.localizedDescription, time: 2)
                onCompletion(false)
            }
        }
    }
}
