//
//  LockOptionViewViewControllerSwift.swift
//  MCPlus
//
//  Created by seo ha on 14/02/2019.
//  Copyright © 2019 KangSH. All rights reserved.
//

import Foundation
import UIKit

class LockOptionViewViewController: UIViewController {
    
    @IBOutlet weak var tableview:UITableView!{
        didSet{
            tableview.delegate = self
            tableview.dataSource = self
            
            let nib = UINib(nibName: cellIdentifier, bundle: nil)
            
            tableview.register(nib, forCellReuseIdentifier: cellIdentifier)
        }
    }
    @IBOutlet weak var navigationbar:UINavigationBar!{
        didSet{
            navigationbar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white]
            navigationbar.barTintColor = UIColor(red: 71/255.0, green: 112/255.0, blue: 178/255.0, alpha: 1.0)
            navigationbar.isTranslucent = false
            let backButton = UIBarButtonItem(title: "", style: .plain, target: navigationController, action: nil)
            
            let rightButton = UIBarButtonItem(barButtonSystemItem: .stop, target: nil, action: #selector(closeOption))
            rightButton.tintColor = UIColor.white
            
            let previousItem = UINavigationItem(title: "암호 잠금")
            previousItem.leftBarButtonItem = backButton
            previousItem.rightBarButtonItem = rightButton
            
            navigationbar.pushItem(previousItem, animated: true)
        }
    }
    @IBOutlet weak var naviTitle:UINavigationItem!
    
    let userDefaults = UserDefaults.standard
    var str_desc:String = "암호를 분실했을 경우 앱을 삭제하고 재설치 해야하며, 재설치 후 암호를 새로 설정하시기 바랍니다."
    
    var itemsInfo:[String:[String]] = {
        var itemsInfo = [String:[String]]()
        
        itemsInfo["1"] = ["암호잠금(필수)"]
        itemsInfo["2"] = ["생체인증(지문)"]
        itemsInfo["3"] = ["암호 변경"]
        
        return itemsInfo
    }()
    
    let cellIdentifier = "LockOptionCell"
    
    deinit {
        Notification.removeNotification(observer: self)
    }
    
    
}

extension LockOptionViewViewController{
    
    func appWillEnterBackground(notification:Notification){
        let lockScreenDao = LockScreenDAO.sharedInstance
        self.dismiss(animated: false, completion: nil)
    }
    
    override func viewDidLoad() {
        Notification.registerNotification(name: UIApplication.didEnterBackgroundNotification, queue: .main, block: appWillEnterBackground)
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    @objc func closeOption(){
        print("close.......")
        self.dismiss(animated: false, completion: nil)
    }
    
    @objc func switchChanged(sender:UISwitch?){
        print("The tag is  \(sender?.tag)")
        print("The switch is \(sender?.isOn == true ? "ON" : "OFF")")
        
        // 어차피 현재 스위치 태그는 다 0임.
        userDefaults.set(sender?.isOn == true ? "ON" : "OFF", forKey: "fingerprint")
        
    }
}

//MARK: - UITableview delegate & datasource
extension LockOptionViewViewController:UITableViewDelegate, UITableViewDataSource{
    
    func numberOfSections(in tableView: UITableView) -> Int {
        // Return the number of sections.
        return itemsInfo.map({$0.key}).count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        let key = itemsInfo.map({$0.key})[section]
        
        return itemsInfo[key]?.count ?? 0
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! LockOptionCell
    
        cell.selectionStyle = .none
        
        let key = itemsInfo.map({$0.key})[indexPath.section]
        cell.label.text = itemsInfo[key]?[indexPath.row] ?? ""
        cell.switchButton.tag = indexPath.row
        
        cell.switchButton.addTarget(self, action: #selector(switchChanged(sender:)), for: .valueChanged)
        cell.switchButton.isEnabled = false
        
        switch indexPath.section {
        case 1:
            cell.switchButton.isEnabled = true
            if let temp = userDefaults.object(forKey: "fingerprint") as? String{
                cell.switchButton.isOn = temp == "ON"
            }else{
                cell.switchButton.isOn = true
            }
        case 2:
            cell.switchButton.isHidden = true
        default:
            break
        }
        
        
        return cell
        
        
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "" //[[itemsInfo allKeys] objectAtIndex:section];
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 44
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        // calculate height of UILabel
        let lblSectionName = UILabel()
        
        lblSectionName.text = self.str_desc
        lblSectionName.textColor = UIColor.lightGray
        lblSectionName.numberOfLines = 0
        lblSectionName.lineBreakMode = .byWordWrapping
        lblSectionName.backgroundColor = UIColor.lightGray
        lblSectionName.frame = CGRect(x: 20, y: 15, width: Constants.kScreenWidth-30, height: lblSectionName.frame.width)
        lblSectionName.sizeToFit()
        
        //푸터 설정
        if section == 2 {
            return lblSectionName.frame.size.height + 30
        }
        
        return 0
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footerView = UIView()
        let lblSectionName = UILabel()
        
        lblSectionName.text = self.str_desc
        lblSectionName.textColor = UIColor.red
        lblSectionName.numberOfLines = 0
        lblSectionName.lineBreakMode = .byWordWrapping;
        lblSectionName.frame = CGRect(x: 20, y: 15, width: Constants.kScreenWidth-30, height: lblSectionName.frame.width)
        lblSectionName.sizeToFit()
        
        footerView.addSubview(lblSectionName)
        footerView.frame = CGRect(x: 0, y: 0, width: tableView.bounds.width, height: lblSectionName.frame.height)
        footerView.backgroundColor = UIColor(red: 247/255.0, green: 247/255.0, blue: 247/255.0, alpha: 1.0)
        
        if section == 2  {
            return footerView
        }
        return nil
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        print("selected cell is (\(indexPath.section), \(indexPath.row))")
        
        if indexPath.section == 2 {
            // 암호변경화면 호출.
            
            let lockScreenDao = LockScreenDAO.sharedInstance
            lockScreenDao.pwInputType = LockScreenDAO.PASSWORD_INPUT_TYPE.FIRST_INPUT
            lockScreenDao.saveOptionValuesWithoutPassword()
            
            let VC = ScreenLockViewController()
            self.present(VC, animated: true, completion: nil)
        }
    }
    
    
}
