//
//  WebView.swift
//  Astro
//
//  Created by Jeremy Wiebe on 2015-12-09.
//  Copyright © 2015 Mobify Research & Development Inc. All rights reserved.
//

import Foundation
import UIKit
import WebKit

let platformName = "iOS"

public extension UIWebView {
    @objc func injectNativeEnvironment() {
        let envJS = environmentJS()
        self.stringByEvaluatingJavaScript(from: envJS)
    }
}

public extension WKWebView {
    @objc func injectNativeEnvironment() {
        let envJS = environmentJS()
        self.evaluateJavaScript(envJS, completionHandler: nil)
    }
}

private func environmentJS() -> String {
    // Inject 'env' into the webview
    #if DEBUG
        let isDebug = true
    #else
        let isDebug = false
    #endif

    #if ASTRO_PREVIEW
        let isAstroPreview = true
    #else
        let isAstroPreview = false
    #endif

    let osVersion = ProcessInfo.processInfo.operatingSystemVersion
    let versionString = "\(osVersion.majorVersion).\(osVersion.minorVersion).\(osVersion.patchVersion)"

    let configString = "Configuration: { DEBUG: \(isDebug), ASTRO_PREVIEW: \(isAstroPreview) }"
    let osString = "OSInfo: { os: '\(platformName)', version: '\(versionString)'}"
    let envJS = "window.AstroNative = { \(configString), \(osString)}"

    return envJS
}
