//
//  ServiceItemScrollViewController.swift
//  kt
//
//  Created by Alexandr Zalutskiy on 30.01.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit
import WebKit

class ServiceItemScrollViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate, WKUIDelegate, WKNavigationDelegate {
    
    @IBOutlet weak var trueTableView: UITableView!
    @IBOutlet weak var containerHeightConstrant: NSLayoutConstraint!
    @IBOutlet weak var contentView: UIView!
    
    //  @IBOutlet weak var wrapperView: UIView!
    let notificationCenter = NSNotificationCenter.defaultCenter()
    let facade = Facade.sharedInstance()
    var serviceItemForLoading: ServiceItem?
    var serviceItem: ServiceItem?
    let serviceItemImageCell = "serviceItemImageCell"
    let serviceItemWebviewCell = "serviceItemWebviewCell"
    let titleServiceItemCell = "titleServiceItemCell"
    let tariffCell = "tariffCell"
    let serviceItemMoreCell = "serviceItemMoreCell"
    //MARK: UI
    var subviewHeight: NSLayoutConstraint!
    @IBOutlet weak var scrollView: UIScrollView!
    var loadingIndicator: UIActivityIndicatorView?
    @IBOutlet private weak var connectButton: UIButton!
    @IBOutlet private weak var callbackButton: UIButton!
    static let webViewDidFinishedLoading = "webViewDidFinishedLoading"
    var counter = 0
    var webViewLoaded = false
    var webView: WKWebView!
    var webViewHeight: NSLayoutConstraint!
    @IBOutlet weak var webViewWrapperView: UIView!
    var heightForRow: [Int: CGFloat] = [Int: CGFloat]()
    var htmlToLoad : String?
    
    
    @IBAction func connectButton(sender: AnyObject) {
        let vc = self.storyboard!.instantiateViewControllerWithIdentifier("CallbackViewController") as! CallbackViewController
        vc.service_id = serviceItem?.id
        vc.type = 2 // HOT - заказ услуги
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func callBackButton(sender: AnyObject) {
        let vc = self.storyboard!.instantiateViewControllerWithIdentifier("CallbackViewController") as! CallbackViewController
        vc.service_id = serviceItem?.id
        vc.type = 1 // COLD - обратный звонок
        self.navigationController?.pushViewController(vc, animated: 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)
        
        trueTableView.showsVerticalScrollIndicator = false;
        
        if serviceItemForLoading?.type == "software" || serviceItemForLoading?.type == nil {
            wkUController.addUserScript(wkUScript5)
        }
        
        let wkWebConfig = WKWebViewConfiguration()
        wkWebConfig.userContentController = wkUController
        
        
        
        //    let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: webViewWrapperView.frame, configuration: wkWebConfig)
        webView.UIDelegate = self
        webView.navigationDelegate = self
        
        
        
        
        if serviceItemForLoading?.type == "software" || serviceItemForLoading?.type == nil {
            webView = WKWebView(frame: self.view.frame, configuration: wkWebConfig)
            webView.UIDelegate = self
            webView.navigationDelegate = self
            
            webView.translatesAutoresizingMaskIntoConstraints = false
            self.view.addSubview(webView)
            
            
            
            /*webViewWrapperView.addSubview(webView)
             let views = ["webView": webView]
             webViewWrapperView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: [], metrics: nil, views: views))
             webViewWrapperView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[webView]|", options: [], metrics: nil, views: views))*/
        } else {
            webView.configuration.suppressesIncrementalRendering = true
        }
    }
    
    func observeHtml(html: String) -> String {
        //<meta name=\"viewport\" content=\"width=\(self.trueTableView.frame.size.width), initial-scale=1.0, maximum-scale=1.0, user-scalable=no\" />
        let result = "<html><head><style type=\"text/css\">body,p{font-family:Helvetica Neue; font-size:16px;}</style></head><body>" + html + "</body></html>"
        return result
    }
    
    func configureViews() {
        if serviceItemForLoading?.type == "software" || serviceItemForLoading?.type == nil {
            self.trueTableView.hidden = true
            self.webViewWrapperView.hidden = true
            self.view.bringSubviewToFront(webViewWrapperView)
        } else {
            self.webViewWrapperView.hidden = true
            trueTableView.rowHeight = UITableViewAutomaticDimension
            trueTableView.estimatedRowHeight = 300
            self.trueTableView.hidden = false
            self.view.bringSubviewToFront(self.trueTableView)
            self.trueTableView.dataSource = self
            self.trueTableView.delegate = self
        }
    }
    
    func setServiceItem(notification: NSNotification) {
        self.unregisterForServiceItem()
        self.serviceItem = (notification.userInfo!["item"] as! ServiceItem)
        //self.trueTableView.reloadData()
    }
    
    func unregisterForServiceItem() {
        notificationCenter.removeObserver(
            self,
            name: FacadeItemSuccess,
            object: facade
        )
    }
    
    func registerForServiceItem() {
        notificationCenter.addObserver(
            self,
            selector: #selector(ServiceItemScrollViewController.setServiceItem(_:)),
            name: FacadeItemSuccess,
            object: facade
        )
    }
    
    //MARK: View life cycle
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        print(self.serviceItemForLoading)
        
        //if (serviceItem != nil) {
        //}
        
        configureViews()
        self.navigationItem.title = serviceItemForLoading?.name
        loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .White)
        loadingIndicator!.hidesWhenStopped = true
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: loadingIndicator!)
        loadingIndicator!.startAnimating()
        registerForServiceItem()
        self.webView.scrollView.showsVerticalScrollIndicator = false
        self.trueTableView.allowsSelection = true
        self.processRequest(true)
        if serviceItemForLoading?.type == "software" || serviceItemForLoading?.type == nil {
            //      mclientid=e6c52e77d0536c97fd50d0cec0b6ae0a&maccesstoken=RZEAAOZGTXVTCBVKIVOBPRVHKSRSPUWQFCIMDEPMHQOWEPJCJQRCUQSCSVTQJVWYADGFGKXPLDYUHFKTJIVKLOSXYBCMZLKHUUCKAGSUTPXBWCVBEOAUJPVYFJSFWIWG&mserverid=17&mabonentid=2504444
            var suffixParams = "mclientid=\(Facade.clientId!)&maccesstoken=\(Facade.accessToken!)&mserverid=\(Facade.serverId!)&mabonentid=\(Facade.accountId!)&rs_uri=/action/subscribe/\(serviceItemForLoading?.key ?? "null")"
            //      mclientid=34041d7a2f11b3f96f1e66f66646083b&maccesstoken=GQLMXKMLJTDOBFXWBZOMCAVKZYKYSEEFRAYJYNTJMRBMHJNYIFWKPJFGOVLQORRBUBXZTRFNRQZKKJIIDHJIOJMGWKANFLLGTZMBBTLAWWVZTNPSCUZDADHQMXNYDRTL&mserverid=17&mabonentid=2504444&rs_uri=/action/subscribe/childwebguardian_pro_kzt
            //            "https://telecom.kz/msoftware"
            let mutableReq = NSMutableURLRequest(URL: NSURL(string: "https://telecom.kz/msoftware/?\(suffixParams)")!)
            //      mutableReq.addValue("\(Facade.clientId!)", forHTTPHeaderField: "mclientid")
            //      mutableReq.addValue(Facade.accessToken!, forHTTPHeaderField: "maccesstoken")
            //      mutableReq.addValue("\(Facade.serverId!)", forHTTPHeaderField: "mserverid")
            //      mutableReq.addValue("\(Facade.accountId!)", forHTTPHeaderField: "mabonentid")
            self.webView.loadRequest(mutableReq)
            //      mutableReq.addValue("\(Facade.clientId!)", forHTTPHeaderField: "mclientid")
            //      mutableReq.addValue(Facade.accessToken!, forHTTPHeaderField: "maccesstoken")
            //      mutableReq.addValue("\(Facade.serverId!)", forHTTPHeaderField: "mserverid")
            //      mutableReq.addValue("\(Facade.accountId!)", forHTTPHeaderField: "mabonentid")
            //      request(mutableReq).response { (req, resp, data, error) in
            //        if let error = error {
            //          print(error)
            //        } else {
            //          var convertedString = String(data: data!, encoding: NSUTF8StringEncoding)!
            //          convertedString = convertedString.stringByReplacingOccurrencesOfString("<title></title>", withString: "<title>title</title>")
            //        self.webView.loadHTMLString("<style>img{max-width: 100%; width:auto; height: auto;}</style>" + convertedString, baseURL: nil)
        } else {
            let params: [String: AnyObject] = ["service_id": serviceItemForLoading!.id!, "type": serviceItemForLoading!.type!]
            facade.getLanding(params, onSuccess: { (respServiceItem) in
                
                if (!respServiceItem.isShowConnectButton!) {
                    self.connectButton.hidden = true
                    self.containerHeightConstrant.constant = 80
                }
                
                
                self.htmlToLoad = self.observeHtml(respServiceItem.html)
                
                self.webView.loadHTMLString(self.observeHtml(respServiceItem.html), baseURL: nil)
                
                //            let delay = 1 * Double(NSEC_PER_SEC)
                //            let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
                //            dispatch_after(time, dispatch_get_main_queue(), {() in
                //                self.trueTableView.reloadData()
                //            })
                print("SC: Recieved")
                }, onError: { (error) in
                }, onFinish: {
                    
                    
            })
        }
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //    setBackButton()
        //    configureGrayNavbar()
        configureBlueNavbar()
        localizable()
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        //    scrollView.contentSize.width = scrollView.frame.width
    }
    
    // MARK: public method
    
    func showTariff(rate: ServiceItem.Rate) {
        performSegueWithIdentifier(Segue.ShowTariffSegue, sender: rate)
    }
    
    func openServiceDetails(sender : UIButton) {
        performSegueWithIdentifier(Segue.ShowServiceDetails, sender: sender)
    }
    
    // MARK: Navigation
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        switch segue.identifier! {
        case Segue.ShowTariffSegue:
            let vc = segue.destinationViewController as! ServiceTariffController
            vc.rate = sender as! ServiceItem.Rate
            break
        case Segue.CallbackSegue, Segue.ConnectSegue:
            let vc = segue.destinationViewController as! ServiceCallbackController
            vc.serviceItem = serviceItemForLoading
            vc.type = segue.identifier! == Segue.CallbackSegue ? 1 : 2
            if segue.identifier! == Segue.ConnectSegue {
                vc.title = LS("service.connect")
            }
            break
        default:
            break
        }
        if segue.identifier == Segue.ShowTariffSegue {
            let vc = segue.destinationViewController as! ServiceTariffController
            vc.rate = sender as! ServiceItem.Rate
            //      vc.tariff = sender as! Tariff
            vc.serviceItem = serviceItemForLoading
        } else if ( segue.identifier == Segue.ShowServiceDetails) {
            let vc = segue.destinationViewController as! ServiceDetailsViewController
            vc.htmlToLoad = self.htmlToLoad!
        } else {
            let vc = segue.destinationViewController as! ServiceCallbackController
            vc.serviceItem = serviceItemForLoading
        }
        
    }
    
    // MARK: Helper
    
    private func localizable() {
        connectButton.setTitle(LS("service.connect", description: "Подключить"), forState: .Normal)
        callbackButton.setTitle(LS("service.callback", description: "Обратный звонок"), forState: .Normal)
    }
    
    override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
        super.didRotateFromInterfaceOrientation(fromInterfaceOrientation)
        //    scrollView.contentSize.width = scrollView.frame.width
    }
}

// WKNavigationDelegate
extension ServiceItemScrollViewController {
    
    func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
        
        print("SC: WKWebView didFinishNavigation")
        self.loadingIndicator?.stopAnimating()
        self.trueTableView.reloadData()
        webView.evaluateJavaScript("document.documentElement.outerHTML.toString()",
                                   completionHandler: { (html: AnyObject?, error: NSError?) in
                                    print(html)
                                    
                                    
        })
        self.processRequest(false)
        
    }
    
    
    
    //  func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
    //    NSNotificationCenter.defaultCenter().postNotificationName(ServiceItemScrollViewController.webViewDidFinishedLoading, object: nil)
    //    self.loadingIndicator?.stopAnimating()
    //  }
    
    func wkWebViewContentSizeDefined() {
        NSNotificationCenter.defaultCenter().postNotificationName(ServiceItemScrollViewController.webViewDidFinishedLoading, object: nil)
        trueTableView.beginUpdates()
        trueTableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: self.serviceItem!.image.absoluteString!.isEmpty ? 1 : 2, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
        trueTableView.endUpdates()
        self.loadingIndicator?.stopAnimating()
        self.processRequest(false)
    }
}

// UIWebViewDelegate
extension ServiceItemScrollViewController {
    
    func webViewDidFinishLoad(webView: UIWebView) {
        NSNotificationCenter.defaultCenter().postNotificationName(ServiceItemScrollViewController.webViewDidFinishedLoading, object: nil)
        print("counter: \(counter)")
        counter += 1
        trueTableView.beginUpdates()
        trueTableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: self.serviceItem!.image.absoluteString!.isEmpty ? 1 : 2, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
        trueTableView.endUpdates()
        self.loadingIndicator?.stopAnimating()
        
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
        Router.globalLog.debug("didFailLoadWithError: \(error.debugDescription)")
        AlertViewUtil.showAlert(error.localizedDescription)
        self.loadingIndicator?.stopAnimating()
        //    debugPrint("didFailLoadWithError")
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        return true
    }
}

// MARK: UITableViewDataSource
extension ServiceItemScrollViewController {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if serviceItem != nil {
            if serviceItem!.rates.isEmpty {
                return self.serviceItem!.image.absoluteString!.isEmpty ? 2 : 3
            } else {
                return self.serviceItem!.image.absoluteString!.isEmpty ? serviceItem!.rates.count + 3 : serviceItem!.rates.count + 4
            }
        }
        return 0
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var resultCell = UITableViewCell()
        let fromValue =  self.serviceItem!.image.absoluteString!.isEmpty ? -1 : 0
        var isTarifCell = false
        switch indexPath.row {
        case fromValue:
            let cell = tableView.dequeueReusableCellWithIdentifier(serviceItemImageCell, forIndexPath: indexPath) as! ServiceItemImageCell
            ImageLoader.sharedLoader.imageForUrl(self.serviceItem!.image.absoluteString!, completionHandler: {
                (image : UIImage?, url : String) in
                cell.pictureView.image = image
            })
            resultCell = cell
            break
        case fromValue + 1:
            let cell = tableView.dequeueReusableCellWithIdentifier("serviceImageBottomTitleCell", forIndexPath: indexPath) as! ServiceImageBottomTitleCell
            cell.label.setTextAndSizeToFit(self.serviceItem!.title)
            resultCell = cell
            break
        case fromValue + 2:
            print("SC: TableView Reloading")
            //let cell2 = tableView.dequeueReusableCellWithIdentifier(serviceItemWebviewCell, forIndexPath: indexPath) as! ServiceItemWebviewCell
            let cell = tableView.dequeueReusableCellWithIdentifier(serviceItemMoreCell, forIndexPath: indexPath) as! ServiceItemMoreButtonCell
            cell.vc = self
//            if !self.webViewLoaded {
//                //        self.webView.opaque = false
//                self.webView.userInteractionEnabled = false
//                cell.contentView.addSubview(self.webView)
//                self.webView.translatesAutoresizingMaskIntoConstraints = false
//                let views = ["web": self.webView]
//                cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[web]|", options: [], metrics: nil, views: views))
//                cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[web]|", options: [], metrics: nil, views: views))
//                
//                //self.webView.loadHTMLString("<style>img{max-width: 100%; width:auto; height: auto;}</style>" + self.serviceItem!.html, baseURL: nil)
//                self.webViewHeight = NSLayoutConstraint(item: self.webView, attribute: .Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: 0)
//                self.webView.userInteractionEnabled = true
//                
//                //        cell.webViewHeight.priority = UILayoutPriorityDefaultLow
//                cell.contentView.addConstraint(self.webViewHeight)
//                
//                let delay = 1 * Double(NSEC_PER_SEC)
//                let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))
//                dispatch_after(time, dispatch_get_main_queue(), {() in
//                    self.webViewHeight.constant = self.webView.scrollView.contentSize.height
//                    self.wkWebViewContentSizeDefined()
//                    self.webView.loadHTMLString(self.observeHtml(self.serviceItem!.html), baseURL: nil)
//                    
//                    
//                    
//                })
//                self.webViewLoaded = true
//            } else {
//                self.webView.userInteractionEnabled = false
//                cell.contentView.addSubview(self.webView)
//                self.webView.translatesAutoresizingMaskIntoConstraints = false
//                let views = ["web": self.webView]
//                cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[web]|", options: [], metrics: nil, views: views))
//                cell.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[web]|", options: [], metrics: nil, views: views))
//                cell.contentView.addConstraint(self.webViewHeight)
//                self.webView.userInteractionEnabled = true
//                
//                cell.contentView.setNeedsLayout()
//                
//            }
            resultCell = cell
            break
        case fromValue + 3:
            let cell = tableView.dequeueReusableCellWithIdentifier(titleServiceItemCell, forIndexPath: indexPath) as! TitleServiceItemCell
            //      if serviceItem!.rates.isEmpty {
            //        cell.label.setTextAndSizeToFit("")
            //      } else {
            cell.label.setTextAndSizeToFit(LocalizedString("service.tariffs", description: "Тарифы"))
            //      }
            //cell.backgroundColor = Color.PlaceholderGrayColor
            resultCell = cell
            break
        default:
            let cell = tableView.dequeueReusableCellWithIdentifier(tariffCell, forIndexPath: indexPath)
                as! TariffCell
            let backgroundViewForCell = UIView(frame: cell.contentView.frame)
            backgroundViewForCell.backgroundColor = Color.GrayTableCellSeparator
            cell.selectedBackgroundView = backgroundViewForCell
            cell.label!.setTextAndSizeToFit(serviceItem!.rates[indexPath.row - (fromValue + 4)].name)
            resultCell = cell
            isTarifCell = true
            break
        }
        if (!isTarifCell) {
            resultCell.selectionStyle = .None
        }
        
        if (indexPath.row == 0 || indexPath.row == 1) {
            resultCell.separatorInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, resultCell.bounds.size.width)
        }
        return resultCell
    }
    
}

// MARK: UITableViewDelegate
extension ServiceItemScrollViewController {
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if let tableView = scrollView as? UITableView {
            for cell in tableView.visibleCells {
                guard let cell = cell as? ServiceItemWebviewCell else { continue }
                webView.setNeedsLayout()
            }
        }
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        cell?.selectionStyle = .None
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        let fromVarValue = self.serviceItem!.image == "" ? 2 : 3
        if indexPath.row == 0 {
            //TODO: Нужно ли в действительности открывать по нажатию на картинку окно в браузере?
            //UIApplication.sharedApplication().openURL(serviceItem!.link)
        } else if indexPath.row > fromVarValue {
            showTariff(serviceItem!.rates[indexPath.row - (fromVarValue + 1)])
        }
    }
}
