//
//  SettingsVC.swift
//  WoWonder
//
//  Created by iMac on 05/09/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import UIKit
import SDWebImage
import CoreData
import WowonderMessengerSDK
import Toast_Swift
import Async
import PWSwitch
import OneSignalFramework
import DropDown
import SafariServices
import StoreKit
import LocalAuthentication

class SettingsVC: BaseVC {
    
    // MARK: - IBOutlets
    
    @IBOutlet weak var moreButton: UIButton!
    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var userNameLabel: UILabel!
    @IBOutlet weak var dropDownButton: UIButton!
    @IBOutlet weak var accountView: UIView!
    @IBOutlet weak var accountTableView: UITableView!
    @IBOutlet weak var accountTableViewHeight: NSLayoutConstraint!
    @IBOutlet weak var themeLabel: UILabel!
    @IBOutlet weak var fingerprintLockSwitch: PWSwitch!
    @IBOutlet weak var mobileDataLabel: UILabel!
    @IBOutlet weak var wifiDataLabel: UILabel!
    @IBOutlet weak var privacyFollowMeLabel: UILabel!
    @IBOutlet weak var privacyMessageMeLabel: UILabel!
    @IBOutlet weak var privacyBirthdayLabel: UILabel!
    @IBOutlet weak var onlineUsersSwitch: PWSwitch!
    @IBOutlet weak var notificationPopupButton: UIButton!
    @IBOutlet weak var conversationTonesButton: UIButton!
    
    // MARK: - Properties
    
    private let dropDown = DropDown()
    private var dropDownDataSource = [
        "Invite Friends",
        "Rate our App",
        "About us",
        "Contact Us",
        "Privacy Policy",
        "Terms of Use"
    ]
    var isAddAccount = false
    let socketHelper = SocketHelper.shared
    var isNotificationPopup = false
    var isConversationTones = false
    var switchAccountData: [UserData] = []
    var mobileDataDownload: [String] = []
    var wifiDataDownload: [String] = []
    
    // 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)
    }
    
    // More Button Action
    @IBAction func moreButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.dropDown.show()
    }
    
    // User Profile Button Action
    @IBAction func userProfileButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        self.isAddAccount = !self.isAddAccount
        self.accountView.isHidden = !self.isAddAccount
        let imageName = self.isAddAccount ? "fi-small-up" : "fi-small-down"
        self.dropDownButton.setImage(UIImage(named: imageName), for: .normal)
    }
    
    // Profile Information button Action
    @IBAction func profileInformationButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.dashboard.userProfileViewController() {
            newVC.user_id = AppInstance.instance.userId ?? ""
            newVC.user_data = AppInstance.instance.userProfile
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Account Information Button Action
    @IBAction func accountInformationButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.settings.myAccountVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Blocked Users Button Action
    @IBAction func blockedUsersButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.dashboard.blockedUsersVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Delete Account Button Action
    @IBAction func deleteAccountButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.settings.deleteAccountVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Logout Button Action
    @IBAction func logoutButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let alertVC = R.storyboard.popup.warningAlertVC() {
            alertVC.delegate = self
            alertVC.titleText  = "Warning !"
            alertVC.messageText = "Are you sure you went to log out?"
            alertVC.okText = "YES"
            self.present(alertVC, animated: true, completion: nil)
        }
    }
    
    // Wallpaper Button Action
    @IBAction func wallpaperButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.settings.wallpaperViewController() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Theme Button Action
    @IBAction func themeButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.themeAlertVC() {
            newVC.delegate = self
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Change Password Button Action
    @IBAction func changePasswordButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.settings.changePasswordVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Two Factor Authentication Button Action
    @IBAction func twoFactorAuthenticationButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.settings.twoFactorVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Manage Sessions Button Action
    @IBAction func manageSessionsButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.settings.manageSessionVC() {
            self.navigationController?.pushViewController(newVC, animated: true)
        }
    }
    
    // Fingerprint Lock Switch Action
    @IBAction func fingerprintLockSwitchAction(_ sender: PWSwitch) {
        self.view.endEditing(true)
        if self.isBiometricAuthenticationAvailable() {
            if UserDefaults.standard.getFingerprintLock(Key: Local.FINGERPRINT_LOCK.FingerprintLock) {
                UserDefaults.standard.setFingerprintLock(value: false, ForKey: Local.FINGERPRINT_LOCK.FingerprintLock)
            } else {
                UserDefaults.standard.setFingerprintLock(value: true, ForKey: Local.FINGERPRINT_LOCK.FingerprintLock)
            }
        } else {
            self.showBiometricPermissionDeniedAlert()
        }
        self.setFingerprintLock()
    }
    
    // Mobile Data Button Action
    @IBAction func mobileDataButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.mediaDownloadAlertVC() {
            newVC.delegate = self
            newVC.alertType = .Mobile_Data
            newVC.titleText = "When using mobile data"
            newVC.selectedArray = self.mobileDataDownload
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Wi-Fi Data Button Action
    @IBAction func wifiDataButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.mediaDownloadAlertVC() {
            newVC.delegate = self
            newVC.alertType = .WiFi_Data
            newVC.titleText = "When using Wi-Fi data"
            newVC.selectedArray = self.wifiDataDownload
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Follow Me Button Action
    @IBAction func followMeButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.privacyAlertVC() {
            newVC.delegate = self
            newVC.alertType = .Follow_me
            newVC.titleText = "Who can follow me?"
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
            newVC.noBodyView.isHidden = true
        }
        
    }
    
    // Message Me Button Action
    @IBAction func messageMeButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.privacyAlertVC() {
            newVC.delegate = self
            newVC.alertType = .Message_me
            newVC.titleText = "Who can message me?"
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
            newVC.noBodyView.isHidden = true
        }
    }
    
    // Birthday Button Action
    @IBAction func birthdayButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if let newVC = R.storyboard.popup.privacyAlertVC() {
            newVC.delegate = self
            newVC.alertType = .Birthday
            newVC.titleText = "Who can see my birthday?"
            newVC.modalPresentationStyle = .overCurrentContext
            newVC.modalTransitionStyle = .crossDissolve
            self.present(newVC, animated: true)
        }
    }
    
    // Online Users Switch Action
    @IBAction func onlineUsersSwitchAction(_ sender: PWSwitch) {
        self.view.endEditing(true)
        self.updatePrivacy(key: "status", value: sender.on ? "0" : "1")
    }
    
    // Notification Popup Button Action
    @IBAction func notificationPopupButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if self.isNotificationPopup {
            UserDefaults.standard.setNotificationStatus(value: false, ForKey: Local.NOTIFICATION_RECEIVE.NotificationReceive)
            OneSignal.User.pushSubscription.optOut()
        } else {
            UserDefaults.standard.setNotificationStatus(value: true, ForKey: Local.NOTIFICATION_RECEIVE.NotificationReceive)
            OneSignal.User.pushSubscription.optIn()
        }
        self.setNotificationPopup()
    }
    
    // Conversation Tones Button Action
    @IBAction func conversationTonesButtonAction(_ sender: UIButton) {
        self.view.endEditing(true)
        if self.isConversationTones {
            UserDefaults.standard.setConversationTone(value: false, ForKey: Local.CONVERSATION_TONE.ConversationTone)
        } else {
            UserDefaults.standard.setConversationTone(value: true, ForKey: Local.CONVERSATION_TONE.ConversationTone)
        }
        self.setConversationTones()
    }
    
    // MARK: - Helper Functions
    
    // Initial Config
    func initialConfig() {
        self.setupDropDown()
        self.setTheme()
        self.tableViewSetup()
        self.setUserData()
        self.setDownloadData()
        self.getSwitchAccountData()
        self.setFingerprintLock()
        self.setNotificationPopup()
        self.setConversationTones()
    }
    
    // TableView Setup
    func tableViewSetup() {
        self.accountTableView.delegate = self
        self.accountTableView.dataSource = self
        self.accountTableView.register(UINib(resource: R.nib.accountTableViewCell), forCellReuseIdentifier: R.reuseIdentifier.accountTableViewCell.identifier)
    }
    
    private func setupDropDown() {
        self.dropDown.dataSource = self.dropDownDataSource
        self.dropDown.anchorView = self.moreButton
        self.dropDown.width = 200
        self.dropDown.direction = .bottom
        self.dropDown.bottomOffset = CGPoint(x: -174, y: 34)
        self.dropDown.selectionAction = { [unowned self] (index: Int, item: String) in
            if index == 0 {
                if let newVC = R.storyboard.dashboard.inviteFriendsVC() {
                    self.navigationController?.pushViewController(newVC, animated: true)
                }
            } else if index == 1 {
                if let scene = appDelegate.window?.windowScene {
                    SKStoreReviewController.requestReview(in: scene)
                }
            } else if index == 2 {
                if let url = URL(string: API.WEBSITE_URL.about_us) {
                    let safariViewController = SFSafariViewController(url: url)
                    safariViewController.delegate = self
                    present(safariViewController, animated: true, completion: nil)
                }
            } else if index == 3 {
                if let url = URL(string: API.WEBSITE_URL.contact_us) {
                    let safariViewController = SFSafariViewController(url: url)
                    safariViewController.delegate = self
                    present(safariViewController, animated: true, completion: nil)
                }
            } else if index == 4 {
                if let url = URL(string: API.WEBSITE_URL.privacy_policy) {
                    let safariViewController = SFSafariViewController(url: url)
                    safariViewController.delegate = self
                    present(safariViewController, animated: true, completion: nil)
                }
            } else if index == 5 {
                if let url = URL(string: API.WEBSITE_URL.terms) {
                    let safariViewController = SFSafariViewController(url: url)
                    safariViewController.delegate = self
                    present(safariViewController, animated: true, completion: nil)
                }
            }
            self.dropDown.deselectRow(at: index)
            self.view.endEditing(true)
            self.dropDown.hide()
        }
    }
    
    // Set Theme
    func setTheme() {
        let status = UserDefaults.standard.getDarkMode(Key: "darkMode")
        let isSystemTheme = UserDefaults.standard.getSystemTheme(Key: "SystemTheme")
        if #available(iOS 13.0, *) {
            if isSystemTheme {
                self.themeLabel.text = "Set by Battery saver (Auto)"
            } else {
                if status {
                    self.themeLabel.text = "Dark"
                } else {
                    self.themeLabel.text = "Light"
                }
            }
        }
    }
    
    func setUserData() {
        let imageUrl = URL(string: AppInstance.instance.userProfile?.avatar ?? "")
        let indicator = SDWebImageActivityIndicator.medium
        self.userImageView.sd_imageIndicator = indicator
        DispatchQueue.global(qos: .userInteractive).async {
            self.userImageView.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "user_setting"))
        }
        self.nameLabel.text = AppInstance.instance.userProfile?.name
        self.userNameLabel.text = "@" + (AppInstance.instance.userProfile?.username ?? "")
        self.accountView.isHidden = !self.isAddAccount
        switch AppInstance.instance.userProfile?.follow_privacy {
        case "0":
            self.privacyFollowMeLabel.text = "Everyone"
        case "1":
            self.privacyFollowMeLabel.text = "People i Follow"
        default:
            break
        }
        switch AppInstance.instance.userProfile?.message_privacy {
        case "0":
            self.privacyMessageMeLabel.text = "Everyone"
        case "1":
            self.privacyMessageMeLabel.text = "People i Follow"
        case "2":
            self.privacyMessageMeLabel.text = "No body"
        default:
            break
        }
        switch AppInstance.instance.userProfile?.birth_privacy {
        case "0":
            self.privacyBirthdayLabel.text = "Everyone"
        case "1":
            self.privacyBirthdayLabel.text = "People i Follow"
        case "2":
            self.privacyBirthdayLabel.text = "No body"
        default:
            break
        }
        self.onlineUsersSwitch.setOn(AppInstance.instance.userProfile?.status == "0", animated: true)
    }
    
    func getSwitchAccountData() {
        let getSwitchAccountData = UserDefaults.standard.getSwitchAccountData(Key: "Switch_Account_Data")
        let data = try! JSONSerialization.data(withJSONObject: getSwitchAccountData, options: [])
        self.switchAccountData = try! JSONDecoder().decode([UserData].self, from: data)
        self.accountTableView.reloadData()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            self.accountTableViewHeight.constant = self.accountTableView.contentSize.height
        }
    }
    
    func setFingerprintLock() {
        if !self.isBiometricAuthenticationAvailable() {
            UserDefaults.standard.setFingerprintLock(value: false, ForKey: Local.FINGERPRINT_LOCK.FingerprintLock)
        }
        self.fingerprintLockSwitch.setOn(UserDefaults.standard.getFingerprintLock(Key: Local.FINGERPRINT_LOCK.FingerprintLock), animated: true)
    }
    
    func setDownloadData() {
        self.mobileDataDownload = UserDefaults.standard.getDownloadOption(Key: "Mobile_Data_Download")
        self.wifiDataDownload = UserDefaults.standard.getDownloadOption(Key: "WiFi_Data_Download")
        if self.mobileDataDownload.count == 0 {
            self.mobileDataLabel.text = "No Media"
        } else {
            self.mobileDataLabel.text = self.mobileDataDownload.joined(separator: ", ")
        }
        if self.wifiDataDownload.count == 0 {
            self.wifiDataLabel.text = "No Media"
        } else {
            self.wifiDataLabel.text = self.wifiDataDownload.joined(separator: ", ")
        }        
    }
    
    func setNotificationPopup() {
        self.isNotificationPopup = UserDefaults.standard.getNotification(Key: Local.NOTIFICATION_RECEIVE.NotificationReceive)
        let imageName = self.isNotificationPopup ? "ic_check_red" : "ic_uncheck_red"
        self.notificationPopupButton.setImage(UIImage(named: imageName), for: .normal)
    }
    
    func setConversationTones() {
        self.isConversationTones = UserDefaults.standard.getConversationTone(Key: Local.CONVERSATION_TONE.ConversationTone)
        let imageName = self.isConversationTones ? "ic_check_red" : "ic_uncheck_red"
        self.conversationTonesButton.setImage(UIImage(named: imageName), for: .normal)
    }
    
    @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)
        }
    }
    
    func isBiometricAuthenticationAvailable() -> Bool {
        var error: NSError? = nil
        if LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
            return (error == nil)
        } else {
            return false
        }
    }
    
    func showBiometricPermissionDeniedAlert() {
        let alert = UIAlertController(
            title: "Biometric Authentication Not Enabled",
            message: "You previously denied biometric authentication for this app. To enable it, please go to your device settings.",
            preferredStyle: .alert
        )
        let settingsAction = UIAlertAction(title: "Open Settings", style: .default) { (_) in
            if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
                UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
            }
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alert.addAction(settingsAction)
        alert.addAction(cancelAction)
        present(alert, animated: true, completion: nil)
    }
    
}

// MARK: - Extensions

// MARK: Api Call
extension SettingsVC {
    
    func updatePrivacy(key: String, value: String) {
        if Connectivity.isConnectedToNetwork() {
            Async.background {
                SettingsManager.instance.updatePrivacy(key: key, value: value) { (success, sessionError, serverError, error) in
                    if success != nil {
                        Async.main {
                            self.dismissProgressDialog {
                                AppInstance.instance.fetchUserProfile { _ in
                                    self.setUserData()
                                }
                                self.view.makeToast(success?.message ?? "")
                            }
                        }
                    } 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 ?? "")")
                            }
                        }
                    }
                }
            }
        } else {
            self.dismissProgressDialog {
                self.view.makeToast(InterNetError)
            }
        }
    }
    
}

// MARK: TableView Setup
extension SettingsVC: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.switchAccountData.count + 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.accountTableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.accountTableViewCell.identifier, for: indexPath) as! AccountTableViewCell
        self.setUpAccountName(cell: cell, indexPath: indexPath)
        return cell
    }
    
    func setUpAccountName(cell: AccountTableViewCell, indexPath: IndexPath) {
        if indexPath.row != self.switchAccountData.count {
            let imageUrl = URL(string: self.switchAccountData[indexPath.row].avatar ?? "")
            let indicator = SDWebImageActivityIndicator.medium
            self.userImageView.sd_imageIndicator = indicator
            DispatchQueue.global(qos: .userInteractive).async {
                cell.userImageView.sd_setImage(with: imageUrl, placeholderImage: UIImage(named: "user_setting"))
            }
            cell.userNameLabel.text = self.switchAccountData[indexPath.row].username ?? ""
            cell.verifiedImage.isHidden = self.switchAccountData[indexPath.row].user_id != AppInstance.instance.userProfile?.user_id
        } else {
            cell.userImageView.image = UIImage(named: "addImage")
            cell.userNameLabel.text = "Add Account"
            cell.verifiedImage.isHidden = true
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == self.switchAccountData.count {
            if let newVC = R.storyboard.main.signUpMainVC() {
                newVC.isAddAccount = self.isAddAccount
                self.navigationController?.pushViewController(newVC, animated: true)
            }
        } else {
            self.socketHelper.disconnect()
            let entities = appDelegate.persistentContainer.managedObjectModel.entities
            for entity in entities {
                delete(entityName: entity.name!)
            }
            let user_Session = [
                "user_id": self.switchAccountData[indexPath.row].user_id ?? "",
                "access_token": self.switchAccountData[indexPath.row].access_token ?? ""
            ] as [String: Any]
            UserDefaults.standard.setUserSession(value: user_Session, ForKey: Local.USER_SESSION.User_Session)
            AppInstance.instance.fetchUserProfile { success in
                let newVC = R.storyboard.dashboard.tabBarNav()
                appDelegate.window?.rootViewController = newVC
            }
        }
    }
    
}

// MARK: SFSafariViewControllerDelegate Methods
extension SettingsVC: SFSafariViewControllerDelegate {
    
    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
    
}

// MARK: WarningAlertVCDelegate Methods
extension SettingsVC: WarningAlertVCDelegate {
    
    func chatAlertOKButtonPressed(_ sender: UIButton) {
        self.update()
    }
    
}

// MARK: ThemeAlertVCDelegate Methods
extension SettingsVC: ThemeAlertVCDelegate {
    
    func handleThemeTap(themeType: String) {
        self.themeLabel.text = themeType
        let keyWindow = UIApplication.shared.connectedScenes
            .filter({$0.activationState == .foregroundActive})
            .compactMap({$0 as? UIWindowScene})
            .first?.windows
            .filter({$0.isKeyWindow}).first
        switch themeType {
        case "Light":
            keyWindow?.overrideUserInterfaceStyle = .light
            UserDefaults.standard.setDarkMode(value: false, ForKey: "darkMode")
            UserDefaults.standard.setSystemTheme(value: false, ForKey: "SystemTheme")
        case "Dark":
            keyWindow?.overrideUserInterfaceStyle = .dark
            UserDefaults.standard.setDarkMode(value: true, ForKey: "darkMode")
            UserDefaults.standard.setSystemTheme(value: false, ForKey: "SystemTheme")
        case "Set by Battery saver (Auto)":
            keyWindow?.overrideUserInterfaceStyle = UIScreen.main.traitCollection.userInterfaceStyle
            UserDefaults.standard.setSystemTheme(value: true, ForKey: "SystemTheme")
        default:
            break
        }
    }
    
}

// MARK: MediaDownloadAlertVCDelegate Methods
extension SettingsVC: MediaDownloadAlertVCDelegate {
    
    func handleMediaDownloadSelection(alertType: MediaDownloadAlertType, mediaSelection: [String]) {
        switch alertType {
        case .Mobile_Data:
            UserDefaults.standard.setDownloadOption(value: mediaSelection, ForKey: "Mobile_Data_Download")
            self.mobileDataDownload = UserDefaults.standard.getDownloadOption(Key: "Mobile_Data_Download")
            if self.mobileDataDownload.count == 0 {
                self.mobileDataLabel.text = "No Media"
            } else {
                self.mobileDataLabel.text = self.mobileDataDownload.joined(separator: ", ")
            }
        case .WiFi_Data:
            UserDefaults.standard.setDownloadOption(value: mediaSelection, ForKey: "WiFi_Data_Download")
            self.wifiDataDownload = UserDefaults.standard.getDownloadOption(Key: "WiFi_Data_Download")
            if self.wifiDataDownload.count == 0 {
                self.wifiDataLabel.text = "No Media"
            } else {
                self.wifiDataLabel.text = self.wifiDataDownload.joined(separator: ", ")
            }
        }
        AppInstance.instance.getDownloadMediaData()
    }
    
}

// MARK: PrivacyAlertVCDelegate Methods
extension SettingsVC: PrivacyAlertVCDelegate {
    
    func handlePrivacyTap() {
        self.setUserData()
    }
    
}
