//
//  SettingViewController.swift
//  NearbyStores
//
//  Created by DT Team on 7/18/18.
//  Copyright © DT Team. All rights reserved.
//

import UIKit
import AssistantKit
import DropDown


struct Settings {
    struct Keys {
        static let RECEIVE_NOTIFICATION = "receive_notification"
        static let DISTANCE_UNIT = "distance_unit"
    }
}

class SettingsViewController: UITableViewController {
   
    
    
    @IBOutlet weak var navigationBar: UINavigationBar!
    @IBOutlet weak var navigationBarItem: UINavigationItem!
    
    @IBOutlet weak var languageValue: UILabel!
    @IBOutlet weak var languageLabel: UILabel!
    @IBOutlet weak var languageButton: UIButton!
    @IBAction func languageAction(_ sender: Any) {
        dropDown.show()
    }
        
    @IBOutlet weak var notificationLabel: UILabel!
    @IBOutlet weak var notificationDescription: UILabel!
    
    @IBOutlet weak var notification_switch: UISwitch!
    @IBAction func notification_action(_ sender: Any) {
        let view:UISwitch = sender as! UISwitch
        LocalData.setValue(key: Settings.Keys.RECEIVE_NOTIFICATION, value: view.isOn)
    }
    

    @IBOutlet weak var distanceUnitLabel: UILabel!
    @IBOutlet weak var distanceUnitValue: UILabel!
    
    @IBAction func unitAction(_ sender: Any) {
        
        let unit = LocalData.getValue(key: Settings.Keys.DISTANCE_UNIT, defaultValue: AppConfig.distanceUnit)
       
        
    
        let alert = UIAlertController(title: "Distance unit".localized, message: "Please select a distance unit that you would use in the app".localized, preferredStyle: .alert)

        alert.addAction(UIAlertAction(title: "KM".localized, style: .default, handler: { action in
          
            LocalData.setValue(key: Settings.Keys.DISTANCE_UNIT, value: Distance.Types.Kilometers)
            alert.dismiss(animated: true)
            
            self.distanceUnitValue.text = Distance.Types.Kilometers.localized
            AppConfig.distanceUnit = Distance.Types.Kilometers
        }))
        
        alert.addAction(UIAlertAction(title: "Miles".localized, style: .default, handler: { action in
            
            LocalData.setValue(key: Settings.Keys.DISTANCE_UNIT, value: Distance.Types.Miles)
            alert.dismiss(animated: true)
       
            self.distanceUnitValue.text = Distance.Types.Miles.localized
            AppConfig.distanceUnit = Distance.Types.Miles
        
        }))

        self.present(alert, animated: true)
        
        
    }
    
    
    @IBOutlet weak var termsanduse: UILabel!
    @IBOutlet weak var privacypolicy: UILabel!
    @IBOutlet weak var appversionValue: UILabel!
    @IBOutlet weak var appversionlabel: UILabel!
    
    
    @IBAction func termsanduseAction(_ sender: Any) {
        
        
        if let url = URL(string: AppConfig.Api.terms_of_use_url), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
        
        
    }
    
    @IBAction func pravicyPolicyAction(_ sender: Any) {
        
        if let url = URL(string: AppConfig.Api.privacy_policy_url), UIApplication.shared.canOpenURL(url) {
            if #available(iOS 10, *) {
                UIApplication.shared.open(url)
            } else {
                UIApplication.shared.openURL(url)
            }
        }
        
    }
    
    
    let dropDown = DropDown()
    
    func setupLanguagePicker() {
        
        
        let syncedLanguages = SyncAppConfig.findById(id: "APP_LANGUAGES")
        let items =  syncedLanguages!.getValue(defaultValue: "en:English").split(separator: ",")
        
        var languagesNames:[String] = []
        var languagesCodes:[String] = []
            
        for el in items {
            let d = el.split(separator: ":")
            languagesCodes.append(String(d[0]))
            languagesNames.append(String(d[0])+" - "+String(d[1]))
        }

        // The view to which the drop down will appear on
        dropDown.anchorView = languageButton // UIView or UIBarButtonItem

        // The list of items to display. Can be changed dynamically
        dropDown.dataSource = languagesNames
        
        
        dropDown.selectionAction = { [unowned self] (index: Int, item: String) in
            
            //update view
            languageValue.text = languagesNames[index]
            
            LocalData.setValue(key: "default_language_name", value: languagesNames[index])
            
            //update bundle
            Locale.updateLanguage(code: languagesCodes[index])
            
            //hide drop list
            dropDown.hide()
    
            
            //restart the app
            let alert = UIAlertController(title: "Language Changed".localized, message: "To apply the language you should restart the app".localized, preferredStyle: .alert)
            
            alert.addAction(UIAlertAction(title: "No".localized, style: .default, handler: { action in
                alert.dismiss(animated: true)
            }))
            
            alert.addAction(UIAlertAction(title: "Confirm".localized, style: .default, handler: { action in
               
            
                let sb = UIStoryboard(name: "Splash", bundle: nil)
                let vc: SplashViewController = sb.instantiateViewController(withIdentifier: "splash") as! SplashViewController
                
                vc.modalPresentationStyle = .fullScreen
                self.present(vc, animated: true)
                
                
                alert.dismiss(animated: true)
            }))
            
           
           
            self.present(alert, animated: true)
            
            
        }
        
    }
    

      
      @objc func onBackHandler()  {
          
          if let controller = self.navigationController{
              //controller.navigationBar.isHidden = true
              controller.popViewController(animated: true)
              ////controller.navigationBar.isHidden = false
          }else{
              self.dismiss(animated: true)
          }
          
      }
    
    let topBarTitle: EdgeLabel = {
          
          let titleLabel = EdgeLabel()
          
          titleLabel.text = ""
          titleLabel.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.Appearance.primaryColor)
          titleLabel.font = UIFont.systemFont(ofSize: 20)
          
          return titleLabel
          
      }()
      
      func setupNavBarTitles() {
          
          
          let rect = CGRect(x: 0, y: 0, width: view.frame.width - 32, height: view.frame.height)
          topBarTitle.frame = rect
          topBarTitle.textColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.Appearance.primaryColor)
          topBarTitle.font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17)
          topBarTitle.leftTextInset = 5
          
          
          topBarTitle.text = "Setting".localized
        
        
        
        self.navigationBar.isTranslucent = false
        self.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        self.navigationBar.shadowImage = UIImage()
        self.navigationBar.tintColor = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.Appearance.primaryColor)
          
          self.navigationBarItem.titleView = topBarTitle
          
      }
      
      
      
      func setupNavBarButtons() {
          
          let _color = AppDesignUtils.defaultModeColor(dark: .white, light: Colors.Appearance.primaryColor)

          //arrow back icon
          var arrowImage: UIImage? = nil
          if Utils.isRTL(){
              arrowImage = UIImage.init(icon: .ionicons(.iosArrowForward), size: CGSize(width: 30, height: 30), textColor: Colors.Appearance.darkColor)
          }else{
              arrowImage = UIImage.init(icon: .ionicons(.iosArrowBack), size: CGSize(width: 30, height: 30), textColor: Colors.Appearance.darkColor)
          }
          
          
          let customBarButtonItem = UIBarButtonItem(image: arrowImage!, style: .plain, target: self, action: #selector(onBackHandler))
          customBarButtonItem.setIcon(icon: .ionicons(.iosArrowBack), iconSize: 25, color: _color)
          
          
          self.navigationBarItem.leftBarButtonItems = []
          self.navigationBarItem.rightBarButtonItems = []
          self.navigationBarItem.leftBarButtonItems?.append(customBarButtonItem)
          
      }
      
   

    override func viewDidLoad() {
        super.viewDidLoad()
    
        view.backgroundColor = Colors.Appearance.darkColor
        navigationController?.navigationBar.backgroundColor = Colors.Appearance.primaryColor
        navigationController?.navigationBar.tintColor = .white
        
        let backgroundView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: self.tableView.bounds.size.height))
        backgroundView.backgroundColor = UIColor.groupTableViewBackground
        self.tableView.backgroundView = backgroundView
        
        
        self.view.backgroundColor = Colors.Appearance.darkColor
        
        notificationLabel.initBolodFont()
        notificationDescription.initDefaultFont()
      
        distanceUnitLabel.initBolodFont()
        distanceUnitValue.initDefaultFont()
        termsanduse.initDefaultFont()
        appversionlabel.initBolodFont()
        appversionValue.initDefaultFont()
        privacypolicy.initDefaultFont()
        
        
        notificationLabel.text = "Application notifications".localized
        notificationDescription.text = "Receive notifications".localized
        
     
        distanceUnitLabel.text = "Distance unit".localized
        let unit = LocalData.getValue(key: Settings.Keys.DISTANCE_UNIT, defaultValue: AppConfig.distanceUnit)
        distanceUnitValue.text = unit.localized

        termsanduse.text = "Terms of use".localized
        privacypolicy.text = "Privacy Policy".localized
        appversionlabel.text = "Application Version".localized
        
        if(AppConfig.DEBUG){
            for (key,value) in Localization.list_to_translate{
                print("\"\(key)\" = \"\(value)\";")
            }
        }
        
       
        notification_switch.isOn = LocalData.getValue(key: Settings.Keys.RECEIVE_NOTIFICATION, defaultValue: true)!
       
        //First get the nsObject by defining as an optional anyObject
        let nsObject: AnyObject? = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as AnyObject
        //Then just cast the object as a String, but be careful, you may want to double check for nil
        let version = nsObject as! String
        
        if(AppConfig.DEBUG){
            
            if let guest = Guest.getInstance(){
                self.appversionValue.text = "\(version) / Guest ID \(guest.id)"
            }else{
                self.appversionValue.text = "\(version)"
            }
           
        }else{
            self.appversionValue.text = "\(version)"
        }
        
        
        
        
        setupNavBarTitles()
        setupNavBarButtons()
        
        
        setupLanguagePicker()
        languageLabel.initBolodFont()
        languageValue.initDefaultFont()
        languageLabel.text = "Language".localized
        languageValue.text = LocalData.getValue(key: "default_language_name",defaultValue: "English")
    
        
    }

    
    
    override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        let headerView = view as! UITableViewHeaderFooterView
        
        headerView.textLabel?.textColor = Colors.Appearance.primaryColor.withAlphaComponent(0.8)
        let font = UIFont(name: AppConfig.Design.Fonts.regular, size: 17.0)
        headerView.textLabel?.font = font!
        
       // headerView.textLabel?.text = headerView.textLabel?.text?.localized
        
    }



    /*
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

        // Configure the cell...

        return cell
    }
    */

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}


extension Locale {
    
    static func updateLanguage(code: String) {
        
        LocalData.setValue(key: "default_language", value: code)
        
        let isLanguageRTL = Locale.characterDirection(forLanguage: code) == .rightToLeft
        UIView.appearance().semanticContentAttribute = isLanguageRTL == true ? .forceRightToLeft : .forceLeftToRight
    
        UserDefaults.standard.set(isLanguageRTL,   forKey: "AppleTe  zxtDirection")
        UserDefaults.standard.set(isLanguageRTL,   forKey: "NSForceRightToLeftWritingDirection")
        UserDefaults.standard.set([code], forKey: "AppleLanguages")
        UserDefaults.standard.set(code, forKey: "AppleLanguage")
        UserDefaults.standard.set(code, forKey: "i18n_language")
        
        UserDefaults.standard.synchronize()
        
        guard let path = Bundle.main.path(forResource: code, ofType: "lproj") else {
            return
        }
   
    }
    
}

