/*
 *  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 ChooseProvisionerView: UIViewController {
    
    @objc static var haveProvisioningError: Bool = false

    @IBOutlet weak var fileProvisionerButton: UIButton!
    @IBOutlet weak var networkProvisionerButton: UIButton!
    @IBOutlet weak var withPoliciesLabelOutlet: UILabel!
    @IBOutlet weak var withPoliciesSwitchOutlet: UISwitch!
    
    // Requires the application to create Main.storyboard
    // and an intial view controller
    @objc var MainStoryboard: UIStoryboard? = nil

    @IBAction func unwindToChooseProvisioner(segue: UIStoryboardSegue) {
        print ("in unwind segue")
    }
    
    private func toggleWithPolicies(withPolicies:Bool) {
        if withPoliciesSwitchOutlet.isOn {
            withPoliciesLabelOutlet.text = "Use device policies"
        } else {
            withPoliciesLabelOutlet.text = "Do not use device policies"
        }
    }
    
    @IBAction func withPoliciesSwitchAction(_ sender: UISwitch) {
        // Set the the state from the withPolicesSwitch
        Provisioning.setWithPolicies(withPolicies:sender.isOn)
        toggleWithPolicies(withPolicies: Provisioning.getWithPolicies())
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Provisioning.getWithPolicies() uses the global WITH_POLCIIES
        // variable defined in Constants.swift. The default value is false.
        // This means that the Device code should choose a code path
        // that does not use policies.
        // See withPoliciesSwitchAction.
        withPoliciesSwitchOutlet.isOn = Provisioning.getWithPolicies()
        toggleWithPolicies(withPolicies: withPoliciesSwitchOutlet.isOn)
    }
    
    // Load any provisioning information if it exists.
    // First check for bundled provisioning information "TrustStore.plist"
    // and then for saved information from previous runs "prov.plist"
    func staticProvisioning() throws -> Bool {
        var settings:StaticSettings? = try loadBundledSettings()
        if settings == nil {
            settings = try loadLastSettings()
        }
        if let settings = settings {
            Provisioning.setProvisioningStatic()
            Provisioning.setProvisioningFilePath(pf: settings.path)
            Provisioning.setProvisioningPassword(pp: settings.password)
            // TODO: If we can rely on some action that always saves the
            // information we can remove the old one here.
            //removeLastSettingsFile()
            return true
        } else {
            return false
        }
    }

    // If the device has provisioning information proceed to the the
    // DeviceDetailView or display the ChooseProvisionerView
    override func viewWillAppear(_ animated: Bool) {
        do {
            let provisioned = try staticProvisioning()
            if ChooseProvisionerView.haveProvisioningError || !provisioned {
                // Display the ChooseProvisionerView
                ChooseProvisionerView.haveProvisioningError = false
                super.viewWillAppear(animated)
            } else {
                // Have provisioning infomation go right to the App initial view
                // Every App that wants to use generic File and Network bootstrapping
                // must have an "Main" storyboard with at one view controller
                // tagged as the "initial view controller"
                if self.MainStoryboard == nil {
                    self.MainStoryboard = UIStoryboard(name: "Main", bundle: nil)
                }
                self.navigationController?.pushViewController(
                    (self.MainStoryboard?.instantiateInitialViewController())!,
                    animated: animated)
                
            }
        } catch {
            print(error)
            super.viewWillAppear(animated)
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
