//
//  SoftwareRentViewController.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 23.06.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit
import WebKit

class SoftwareRentViewController: ViewControllerWithMenu, UIWebViewDelegate, WKUIDelegate, WKNavigationDelegate {
    
    @IBOutlet weak var progressView: UIProgressView!
    //  @IBOutlet weak var webView: UIWebView!
    var webView: WKWebView!
//    var loadingIndicator : UIActivityIndicatorView?
    var loaded = false
    var counter = 0
    var firstLoaded = true
    
    override func loadView() {
        
        super.loadView()
        
        let jScript = "var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);"
        let jScript2 = "var meta2 = document.createElement('meta'); meta2.setAttribute('content', 'true'); meta2.setAttribute('name', 'HandheldFriendly'); document.getElementsByTagName('head')[0].appendChild(meta2);"
        let jScript3 = "var meta3 = document.createElement('meta'); meta3.setAttribute('content', 'width'); meta3.setAttribute('name', 'MobileOptimized'); document.getElementsByTagName('head')[0].appendChild(meta3);"
        let jScript4 = "var meta4 = document.createElement('meta'); meta4.setAttribute('content', 'yes'); meta4.setAttribute('name', 'apple-mobile-web-app-capable'); document.getElementsByTagName('head')[0].appendChild(meta4);"
        let jScript5 = "var meta5 = document.createElement('style'); meta5.setAttribute('type', 'text/css'); meta5.innerHTML = 'body,p{font-family:Helvetica Neue; font-size:16px;margin:10px;}'; document.getElementsByTagName('head')[0].appendChild(meta5);"
        
        let wkUScript = WKUserScript(source: jScript, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
        let wkUScript2 = WKUserScript(source: jScript2, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
        let wkUScript3 = WKUserScript(source: jScript3, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
        let wkUScript4 = WKUserScript(source: jScript4, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
        let wkUScript5 = WKUserScript(source: jScript5, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
        let wkUController = WKUserContentController()
        
        wkUController.addUserScript(wkUScript)
        wkUController.addUserScript(wkUScript2)
        wkUController.addUserScript(wkUScript3)
        wkUController.addUserScript(wkUScript4)
        wkUController.addUserScript(wkUScript5)
        
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.userContentController = wkUController
        webView = WKWebView(frame: self.view.frame, configuration: wkWebConfig)
        webView.UIDelegate = self
        webView.navigationDelegate = self
        webView.translatesAutoresizingMaskIntoConstraints = false
        webView.scrollView.showsVerticalScrollIndicator = false
        
        let views = ["web": webView]
        self.view.addSubview(webView)
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[web]|", options: [], metrics: nil, views: views))
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[web]|", options: [], metrics: nil, views: views))
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureRightIndicator()
        loadingIndicator?.startAnimating()
        configureBlueNavbar()
        var suffixParams = "mclientid=\(Facade.clientId!)&maccesstoken=\(Facade.accessToken!)&mserverid=\(Facade.serverId!)&mabonentid=\(Facade.accountId!)"
        let mutableReq = NSMutableURLRequest(URL: NSURL(string: "http://telecom.kz/msoftware?\(suffixParams)")!)
        webView.loadRequest(mutableReq)
        Router.globalLog.debug("softwareRent started")
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localize()
    }
    
//    func configureRightIndicator() {
//        loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
//        loadingIndicator?.color = .whiteColor()
//        loadingIndicator!.hidesWhenStopped = true
//        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: loadingIndicator!)
//    }
}

// WKNavigationDelegate
extension SoftwareRentViewController {
    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        loadingIndicator?.stopAnimating()
    }
}

// UIWebViewDelegate
extension SoftwareRentViewController {
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        //    Router.globalLog.debug(request)
        //    Router.globalLog.debug(request.allHTTPHeaderFields)
        //    Router.globalLog.debug(request.HTTPBody)
        //    //    let superValue = [ super webView:theWebView shouldStartLoadWithRequest:request navigationType:navigationType ];
        //    let inIframe = !self.doesRequest(request, webView: webView)
        //    let fromUserInteraction = (navigationType == UIWebViewNavigationType.LinkClicked || navigationType == UIWebViewNavigationType.FormSubmitted)
        //    print("inIFrame: \(inIframe) fromUserInteraction: \(fromUserInteraction)")
        //    print("all headers: \(request.allHTTPHeaderFields!)")
        //
        //    let mutableRequest = NSMutableURLRequest(URL: request.URL!)
        //    print ("HTTPMethod: \(request.HTTPMethod!)")
        //    //    mutableRequest.addValue("sdfgvasdfg8dcv8iz90xcbu09asdfub0a9ub0scj9a", forHTTPHeaderField: "epktoken")
        //    mutableRequest.addValue("\(Facade.clientId!)", forHTTPHeaderField: "mclientid")
        //    mutableRequest.addValue(Facade.accessToken!, forHTTPHeaderField: "maccesstoken")
        //    mutableRequest.addValue("\(Facade.serverId!)", forHTTPHeaderField: "mserverid")
        //    mutableRequest.addValue("\(Facade.accountId!)", forHTTPHeaderField: "mabonentid")
        //    mutableRequest.allHTTPHeaderFields?.update(Manager.defaultHTTPHeaders)
        //    mutableRequest.HTTPMethod = request.HTTPMethod!
        //    print("changedHeaders: \(mutableRequest.allHTTPHeaderFields!)")
        //
        //    let containToken = request.allHTTPHeaderFields!.keys.contains("mclientid") && request.allHTTPHeaderFields!.keys.contains("maccesstoken") && request.allHTTPHeaderFields!.keys.contains("mserverid") && request.allHTTPHeaderFields!.keys.contains("mabonentid")
        //
        //    if (!containToken) {
        //      webView.loadRequest(mutableRequest)
        //    }
        
        return true
    }
    
    func doesRequest(request: NSURLRequest, webView: UIWebView) -> Bool {
        // sees if the mainDocumentURL of the request matches that of the webView
        // if not, is probably from an iFrame
        if let reqMainDocUrl = request.mainDocumentURL, let webViewMainDocUrl = webView.request?.mainDocumentURL {
            return reqMainDocUrl.absoluteString!.compare(webViewMainDocUrl.absoluteString!) == NSComparisonResult.OrderedSame
        }
        return false
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        //    print("webViewDidFinishLoad")
        Router.globalLog.debug("webViewDidFinishLoad")
        //    webView.scalesPageToFit = true
        
        //    webView.stringByEvaluatingJavaScriptFromString("document.getElementsByTagName('body')[0].style.fontSize = '30px'")
        //    let contentSize = webView.scrollView.contentSize
        //    let viewSize = webView.bounds.size
        //
        //    let rw:CGFloat = viewSize.width / contentSize.width
        //
        //    webView.scrollView.minimumZoomScale = rw
        //    webView.scrollView.maximumZoomScale = rw
        //    webView.scrollView.zoomScale = rw
        
        counter += 1
        if counter >= 2 {
            loadingIndicator?.stopAnimating()
        }
        print("counter: \(counter)")
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        //    print("webViewDidStartLoad")
        //    Router.globalLog.debug(req)
        //    Router.globalLog.debug(resp)
        //    Router.globalLog.debug(json)
        Router.globalLog.debug("webViewDidStartLoad")
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
        Router.globalLog.debug("didFailLoadWithError: \(error.debugDescription)")
        loadingIndicator?.stopAnimating()
        //    debugPrint("didFailLoadWithError")
    }
}

extension SoftwareRentViewController {
    override var localizedId: String {
        return "software_rent"
    }
}
