/*
 *  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 Foundation
import UIKit

internal func showError(controller: UIViewController, alertTitle: String,
        message: String, actionTitle: String,
        handler: ((UIAlertAction) -> Void)?) -> Void {
    
    let alertController = UIAlertController(title: alertTitle, message:
        message, preferredStyle: .alert)
    let defaultAction = UIAlertAction(title: actionTitle, style: .default,
                                      handler: handler)
    alertController.addAction(defaultAction)
    controller.present(alertController, animated: true, completion: nil)
    return
}

/*
 * Load the setting file TrustStore.plist from the Bundle resources and return 
 * a path and password to the
 * provisioning file
 */
func loadSettingFilePath() throws -> (path: String?, password: String?) {
    guard let url = Bundle.main.url(forResource: "TrustStore",
                                    withExtension: "plist") else {
        return (nil, nil)
    }
    
    guard let dict = getPropertyList(url: url) else {
        return (nil, nil)
    }
    
    guard let filename:String = dict["filename"] as? String else {
        return (nil, nil)
    }
    if filename == "" {
        return (nil, nil)
    }
    guard let passphrase:String = dict["password"] as? String else {
        throw SettingError.setting(message: "No password in configuration file")
    }
    if passphrase == "" {
        throw SettingError.setting(message: "No password in configuration file")
    }
    
    let fileextension:String? = dict["fileextension"] as? String ?? ""
    let subdirectory:String? = dict["subdirectory"] as? String  ?? ""
    
    if let filepath = Bundle.main.path(forResource: filename,
                                       ofType: fileextension,
                                       inDirectory: subdirectory) {
        return (filepath, passphrase)
    } else {
        throw SettingError.setting(message:
            "No valid path for the provisioning file \(filename)")
    }
}

func createErrorMessage(sampleName: String) -> String {
   return "Failing initializing of \(sampleName). Please check the chosen provisioning file."

}

public enum SettingError : Error {
    case setting(message: String)
}

func saveProvisioningFile(url: URL, path: String, password: String) {

    var dict: Dictionary<String, Any> =
        ["XInitializerItem" : "DoNotEverChangeMe"]
    dict["path"] = path
    dict["password"] = password

    var err:NSError?
    if let out: OutputStream = OutputStream(url: url, append: false) {
        out.open()
        PropertyListSerialization.writePropertyList(dict,to: out,
        format: PropertyListSerialization.PropertyListFormat.binary,
        options: PropertyListSerialization.WriteOptions(
            Data.WritingOptions.atomic.rawValue),
            error: &err)
        if (err != nil) {
            print(err!)
        }
        defer {
            out.close()
        }
    } else {
        print("Cannot save property list \(url)")
    }
}

func getPropertyList(url: URL) -> Dictionary<String, Any>? {
    do {
        let data = try Foundation.Data(contentsOf: url)
        let plist = try PropertyListSerialization.propertyList(from: data,
            options: .mutableContainers, format: nil)
        return (plist as? Dictionary<String, Any>)!
    } catch {
        print(error)
        return nil
    }
}

