/*
 *  Copyright © 2016, 2017, Oracle and/or its affiliates. All rights reserved.
 *  This software is dual-licensed to you under the MIT License (MIT) and
 *  the Universal Permissive License (UPL). See the LICENSE file in the root
 *  directory for license terms. You may choose either license, or both.
 */

import UIKit

class ProvisioningView: UIViewController, UIPickerViewDataSource,
                                          UIPickerViewDelegate {
    
    var pickerDataSource: Array<String> = []
    var pathList: Array<String> = []
    
    @IBOutlet weak var oracleLogoImageViewOutlet: UIImageView! {
        didSet {
            oracleLogoImageViewOutlet.image = UIImage(named: "oracle_iot.png")
        }
    }
    
    @IBOutlet weak var filePickerOutlet: UIPickerView!
    
    @IBOutlet weak var passwordTextFieldOutlet: UITextField!
    
    @IBOutlet weak var headLineLabelOutlet: UILabel!
    
    @IBOutlet weak var provFileLabelOutlet: UILabel!
    
    @IBOutlet weak var passwordLabelOutlet: UILabel!
    
    @IBOutlet weak var provisionButtonOutlet: UIButton!  {
        didSet {
            provisionButtonOutlet.layer.cornerRadius = 6.0
            provisionButtonOutlet.layer.borderColor = UIColor.lightGray.cgColor
            provisionButtonOutlet.layer.borderWidth = 1.0
            provisionButtonOutlet.layer.backgroundColor = UIColor(white: 0.90,
                                                                  alpha: 1.0).cgColor
        }
    }
    
    @IBOutlet var viewControllerOutlet: UIView!  {
        didSet {
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        var path: String?
        var password: String?
        var errorMessage = String()
        
        do {
            // Load the truststore file.
            let setting = try loadSettingFilePath()
            path = setting.path
            password = setting.password
        } catch SettingError.setting(let message) {
            print(message)
            errorMessage = message
            showError(controller: self,
                      alertTitle: "Device Initialization Alert",
                      message: errorMessage, actionTitle: "Exit App",
                      handler: { (action:UIAlertAction) -> Void in exit(0)})
        } catch {
            errorMessage = "Other error while trying to read TrustStore.plist"
            print(errorMessage)
            showError(controller: self,
                      alertTitle: "Device Initialization Alert",
                      message: errorMessage, actionTitle: "Exit App",
                      handler: { (action:UIAlertAction?) -> Void in exit(0)})
        }
        
        if path != nil {
            // Provisioning data provided with bundle.
            DataConnector.setProvisioningStatic()
            DataConnector.setProvisioningFilePath(pf: path!)
            DataConnector.setProvisioningPassword(pp: password!)
            let secondViewController = self.storyboard?.instantiateViewController(
                withIdentifier: "DeviceDetailView") as! DeviceDetailView
            self.navigationController?.pushViewController(secondViewController,
                                                          animated: false)
        } else {
            let parser = FileParser.sharedInstance
            let path = parser.documentsURL().appendingPathComponent("prov.plist",
                                                                    isDirectory: false)
            if parser.filemgr.fileExists(atPath: path.path) {
                // Provisioning data saved in a previous session exist.
                if let provDict = getPropertyList(url: path) {
                    DataConnector.setProvisioningFilePath(
                        pf: parser.documentsURL().appendingPathComponent(
                            provDict["path"] as! String).path)
                    DataConnector.setProvisioningPassword(
                        pp: provDict["password"] as! String)
                    do {
                        try parser.filemgr.removeItem(atPath: path.path)
                    } catch {
                        print("Issue while trying to delete stored provisioning data")
                    }
                } else {
                    print("Could not load stored provisioning data")
                }
                let secondViewController = self.storyboard?.instantiateViewController(
                    withIdentifier: "DeviceDetailView") as! DeviceDetailView
                self.navigationController?.pushViewController(secondViewController,
                                                              animated: false)
            } else {
                UIGraphicsBeginImageContext(CGSize(width: self.view.frame.size.width,
                                                   height: self.view.frame.size.width - 18))
                UIImage(named: "cloudes-sw.png")?.drawAsPattern(in: self.view.bounds)
                let image : UIImage = UIGraphicsGetImageFromCurrentImageContext()!
                UIGraphicsEndImageContext()
                viewControllerOutlet.backgroundColor = UIColor(patternImage: image)
        
                self.pickerDataSource = makePickerList()
                self.filePickerOutlet.dataSource = self
                self.filePickerOutlet.delegate = self
                provisionButtonOutlet.setTitle(kProvisionApp, for: UIControlState())
                self.provisionButtonOutlet.isEnabled = false
            }
        }
    }
    
    // Create the file list.
    func makePickerList() -> [String] {
        let parser = FileParser.sharedInstance
        let path = parser.documentsURL()
        let files: [FileRep] = parser.filesForDirectory(directoryURL: path)
        var list = Array(repeating: "", count: files.count)
        pathList = Array(repeating: "", count: files.count)
        var relevantCount: Int = 0
        for file in files {
            list[relevantCount] = file.getDisplayName()
            pathList[relevantCount] = file.filePath.path
            relevantCount += 1
        }
        return list
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        headLineLabelOutlet.text = kProvHeadline
        provFileLabelOutlet.text = kProvFileLabel
        passwordLabelOutlet.text = kProvPasswLabel
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int,
                    inComponent component: Int) {
        self.passwordTextFieldOutlet.text = ""
        self.provisionButtonOutlet.isEnabled = false
    }
    
    func pickerView(_ pickerView: UIPickerView,
                    numberOfRowsInComponent component: Int) -> Int {
        return pickerDataSource.count
    }
    
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int,
                    forComponent component: Int) -> String? {
        return pickerDataSource[row]
    }
    
    @nonobjc func pickerView(_ pickerView: UIPickerView, viewForRow row: Int,
                             ForComponent component: Int,
                             reusingView view: UIView?) -> UIView {
        var label = view as! UILabel!
        if label == nil {
            label = UILabel()
        }
        let data = pickerDataSource[row]
        let title = NSAttributedString(string: data,
                attributes: [NSFontAttributeName: UIFont.systemFont(ofSize: 6.0,
                                                                    weight: UIFontWeightRegular)])
        label?.attributedText = title
        label?.textAlignment = .left
        return label!
    }
    
    @IBAction func passwordEditingChanged(_ sender: UITextField) {
        if(sender.text == nil) || (sender.text!.isEmpty) ||
            (self.filePickerOutlet.numberOfRows(inComponent: 0) == 0) {
            self.provisionButtonOutlet.isEnabled = false
        } else {
            self.provisionButtonOutlet.isEnabled = true
        }
    }
    
    // Action associated to the provisioning button.
    @IBAction func onProvisionButton(_ sender: UIButton) {
        let path: String = pathList[filePickerOutlet.selectedRow(inComponent: 0)]
        DataConnector.setProvisioningFilePath(pf: path)
        DataConnector.setProvisioningPassword(pp: passwordTextFieldOutlet.text!)
    }
    
}

