//
//  GMWebEngine.swift
//  GMDoctor
//
//  Created by Thierry on 16/6/21.
//  Copyright © 2016年 Gengmei. All rights reserved.
//

import Foundation
import WebKit
//import GMUtil
//import EVReflection

class GMWebEngine {
    
    var cookies: [String] = []
    weak var webView: WKWebView?
    
    /// WKScriptMessageHandler
    /// 添加一个名称，就可以让JS通过这个名称发送消息：valueName自定义名字
    /// window.webkit.messageHandlers.valueName.postMessage({body: 'xxx'})
    public var scriptMessageHandlerArray: [String] = [String]()
    
    /// 默认最小字体字体
    public var minFontSize: CGFloat = 0
    
    /// 显示滚动条
    public var isShowScrollIndicator: Bool = true
    
    /// 开启手势交互
    public var isAllowsBackForwardGestures: Bool = true
    
    /// 是否允许加载javaScript
    public var isjavaScriptEnabled: Bool = true
    
    /// 是否允许JS自动打开窗口的，必须通过用户交互才能打开
    public var isAutomaticallyJavaScript: Bool = true
    
    /// 是否影藏进度条
    public var isProgressHidden: Bool = false
    
    /// 进度条高度
    public var progressHeight: CGFloat = 1
    
    /// 默认颜色
    public var progressTrackTintColor: UIColor = UIColor.mainVisual
    
    /// 加载颜色
    public var progressTintColor: UIColor = UIColor.mainVisual
    
    init() {
        syncCookies()
    }
    
    /**
     同步Cookie
     WKWebView不再和NSURLSession共享Cookie，所以需要手动同步
     */
    func syncCookies() {
        for cookie in HTTPCookieStorage.shared.cookies(for: URL(string: GMServerDomains.apiHost)!)! {
            let value = "\(cookie.name)=\(cookie.value)"
            cookies.append(value)
        }
    }
    
    /**
     构造Ajax Cookie的Script
     in 2.3.0
     
     - returns script
     */
    func ajaxCookie() -> String {
        var source = ""
        for cookie in HTTPCookieStorage.shared.cookies(for: URL(string: GMServerDomains.apiHost)!)! {
            var string = "\(cookie.name)=\(cookie.value);domain=\(cookie.domain);path=\(cookie.path); expires=\(String(describing: cookie.expiresDate))"
            if cookie.isSecure {
                string = "\(string);secure=true"
            }
            
            source.append("document.cookie='\(string)';")
        }
        return source
    }
    
    func webCookie() -> String {
        return cookies.joined(separator: ";")
//        let cookieStr = cookies.joined(separator: ";")
//        let paraStr = AppDelegate.shareInstance().urlCommonParameters()!.replacingOccurrences(of: "?", with: "")
//        return "\(cookieStr);device_info=\(paraStr)"
    }
    
    /**
     解析全局JS对象
     */
    func parseJSPageData(_ complete: @escaping ([String: AnyObject]) -> Void) {
        webView?.evaluateJavaScript("window.GLOBAL.pagedata") { (object, error) in
            if let data = object as? [String: AnyObject] {
                complete(data)
            }
            debugPrint(error ?? "")
        }
    }
    
}
