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

import UIKit

class ServiceItemContentController: UIViewController, UIWebViewDelegate, UITableViewDataSource, UITableViewDelegate {
    
    let serviceItemImageCell = "serviceItemImageCell"
    let serviceItemWebviewCell = "serviceItemWebviewCell"
    let titleServiceItemCell = "titleServiceItemCell"
    let tariffCell = "tariffCell"
    @IBOutlet weak var webViewHeight: NSLayoutConstraint!
    var testWebview: UIWebView?
    var service: Service?
    var serviceItemForLoading: ServiceItem?
    var pvc: ServiceItemScrollViewController!
    
    private var serviceItem: ServiceItem?
    
    static let webViewDidFinishedLoading = "webViewDidFinishedLoading"
    let notificationCenter = NSNotificationCenter.defaultCenter()
    let facade = Facade.sharedInstance()
    
    private var loadingIndicator: UIActivityIndicatorView?
    private let serviceLogoView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 28))
    
    private var countOfResize: Int = 0 {
        didSet {
            if countOfResize == 3 {
                //        tariffsTableView.layoutIfNeeded()
                //        self.view.layoutIfNeeded()
                //        pvc.scrollView.contentSize.height = tariffsTableView.frame.maxY + 64.0
                //        if serviceItem!.rates.count == 0 {
                //          pvc.scrollView.contentSize.height -= 35.0
                //        }
                //
                //        view.frame.size.height = pvc.scrollView.contentSize.height
                
                loadingIndicator!.stopAnimating()
                
                //        imageView.hidden = false
                //        titleLabel.hidden = false
                //        webView.hidden = false
                //
                //        serviceLogoView.hidden = false
                //
                //        if serviceItem!.rates.count != 0 {
                //          tariffsTableView.hidden = false
                //          tariffLabel.hidden = false
                //        }
            }
        }
    }
    
    // MARK: UI
    
    @IBOutlet private weak var imageView: UIImageView!
    @IBOutlet private weak var titleLabel: UILabel!
    @IBOutlet private weak var webView: UIWebView!
    @IBOutlet private weak var tariffsTableView: UITableView!
    @IBOutlet private weak var tariffLabel: UILabel!
    
    // MARK: View life cycle
    
    override func viewDidLoad() {
        tariffsTableView.rowHeight = UITableViewAutomaticDimension
        tariffsTableView.estimatedRowHeight = 300
        //    titleLabel.text = serviceItemForLoading!.title
        
        loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
        loadingIndicator!.hidesWhenStopped = true
        pvc.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: loadingIndicator!)
        loadingIndicator!.startAnimating()
        
        registerForServiceItem()
        //    if serviceItemForLoading!.type == "software" {
        //      webView.scrollView.contentSize.width = webView.frame.width
        //      webView.delegate = self
        //      webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://telecom.kz/msoftware/\(serviceItemForLoading!.id!)")!))
        //    } else {
        let params: [String: AnyObject] = ["service_id": serviceItemForLoading!.id!, "type": serviceItemForLoading!.type!]
        facade.getLanding(params, onSuccess: { (respServiceItem) in
            //      print(respServiceItem.title)
            }, onError: { (error) in
                //        print(error)
            }, onFinish: {
                
        })
        //    }
        
        //    facade.getServiceItem(
        //      service!,
        //      withId: serviceItemForLoading!.id!,
        //      forCity: CitiesManager.sharedInstance().userCity()
        //    )
        //    testWebview = UIWebView(frame: self.view.frame)
        //    testWebview?.delegate = self
        //    self.view.addSubview(testWebview!)
        //    self.view.bringSubviewToFront(testWebview!)
        
        super.viewDidLoad()
        
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        //    localizable()
    }
    
    //MARK: Helper
    
    private func localizable() {
        //    tariffLabel.text = LocalizedString("service.tariffs", description: "Тарифы")
    }
    
    // MARK: Notifications
    
    func registerForServiceItem() {
        notificationCenter.addObserver(
            self,
            selector: #selector(ServiceItemContentController.setServiceItem(_:)),
            name: FacadeItemSuccess,
            object: facade
        )
    }
    
    func unregisterForServiceItem() {
        notificationCenter.removeObserver(
            self,
            name: FacadeItemSuccess,
            object: facade
        )
    }
    
    // MARK: Facade observering
    
    func setServiceItem(notification: NSNotification) {
        //    dispatch_async(dispatch_get_main_queue()){
        self.unregisterForServiceItem()
        
        self.serviceItem = (notification.userInfo!["item"] as! ServiceItem)
        self.tariffsTableView.dataSource = self
        self.tariffsTableView.delegate = self
        
        //      self.titleLabel.text = self.serviceItem!.title
        //      self.webView.scrollView.contentSize.width = self.webView.frame.width
        //
        //      self.webView.delegate = self
        //
        //      self.webView.loadHTMLString(
        //        "<style>img{max-width: 100%; width:auto; height: auto;}</style>" + self.serviceItem!.html,
        //        baseURL: NSURL(string: "http://pvldev.kaznetmedia.kz/kt/media/upload/")
        //      )
        
        //      let heightForTableView = 43.0 * CGFloat(self.serviceItem!.rates.count)
        //
        //      self.tariffsTableView.addConstraint(
        //        NSLayoutConstraint(
        //          item: (self.tariffsTableView as UIView),
        //          attribute: .Height,
        //          relatedBy: .Equal,
        //          toItem: nil,
        //          attribute: .NotAnAttribute,
        //          multiplier: 1.0,
        //          constant: heightForTableView
        //        )
        //      )
        //      self.tariffsTableView.dataSource = self
        //      self.tariffsTableView.delegate = self
        //      self.pvc.contentView.layoutIfNeeded()
        // TODO: Other method
        //      ImageLoader.sharedLoader.imageForUrl(self.serviceItem!.image.absoluteString!, completionHandler: {
        //        (image : UIImage?, url : String) in
        //
        //        if image != nil {
        //          self.imageView.image = image
        //          self.imageView.addConstraint(
        //            NSLayoutConstraint(
        //              item: self.imageView,
        //              attribute: .Height,
        //              relatedBy: .Equal,
        //              toItem: nil,
        //              attribute: .NotAnAttribute,
        //              multiplier: 1.0,
        //              constant: self.imageView.frame.width * image!.size.height / image!.size.width
        //            )
        //          )
        //
        //          self.imageView.layoutIfNeeded()
        //
        //        }
        //        self.countOfResize += 1
        //      })
        
        //      ImageLoader.sharedLoader.imageForUrl(self.serviceItem!.logo.absoluteString!, completionHandler: {
        //        (image : UIImage?, url : String) in
        //
        //        if image != nil {
        //          self.serviceLogoView.hidden = true
        //          self.serviceLogoView.image = image
        //          self.serviceLogoView.contentMode = .ScaleAspectFit
        //          self.pvc.navigationItem.titleView = self.serviceLogoView
        //        }
        //        self.countOfResize += 1
        //
        //      })
        //    }
    }
}

// MARK: UITableViewDataSource
extension ServiceItemContentController {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if serviceItem != nil {
            return serviceItem!.rates.count + 3
        }
        return 3
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var resultCell = UITableViewCell()
        //    switch indexPath.row {
        //    case 0:
        //      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
        //      })
        //      cell.label.setTextAndSizeToFit(self.serviceItem!.title)
        //      resultCell = cell
        //      break
        //    case 1:
        //      let cell = tableView.dequeueReusableCellWithIdentifier(serviceItemWebviewCell, forIndexPath: indexPath) as! ServiceItemWebviewCell
        //      cell.vc = self
        //      cell.webview.delegate = self
        //      cell.webview.loadHTMLString(
        //        "<style>img{max-width: 100%; width:auto; height: auto;}</style>" + self.serviceItem!.html,
        //        baseURL: NSURL(string: "http://pvldev.kaznetmedia.kz/kt/media/upload/")
        //      )
        //      resultCell = cell
        //      break
        //    case 2:
        //      let cell = tableView.dequeueReusableCellWithIdentifier(titleServiceItemCell, forIndexPath: indexPath) as! TitleServiceItemCell
        //      cell.label.setTextAndSizeToFit(LocalizedString("service.tariffs", description: "Тарифы"))
        //      resultCell = cell
        //      break
        //    default:
        //      let cell = tableView.dequeueReusableCellWithIdentifier(tariffCell, forIndexPath: indexPath)
        //        as! TariffCell
        //      let backgroundViewForCell = UIView(frame: cell.contentView.frame)
        //      backgroundViewForCell.backgroundColor = Color.BlueColorForHighlighted
        //      cell.selectedBackgroundView = backgroundViewForCell
        //      cell.label!.setTextAndSizeToFit(serviceItem!.rates[indexPath.row].name)
        //      resultCell = cell
        //      break
        //    }
        //resultCell.selectionStyle = .None
        return resultCell
    }
    
}

// MARK: UITableViewDelegate
extension ServiceItemContentController {
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        //    pvc.showTariff(serviceItem!.tariffs[indexPath.row])
        pvc.showTariff(serviceItem!.rates[indexPath.row])
    }
}

// UIWebViewDelegate
extension ServiceItemContentController {
    
    func webViewDidFinishLoad(webView: UIWebView) {
        NSNotificationCenter.defaultCenter().postNotificationName(ServiceItemContentController.webViewDidFinishedLoading, object: nil)
        //    webView.addConstraint(
        //      NSLayoutConstraint(
        //        item: webView,
        //        attribute: .Height,
        //        relatedBy: .Equal,
        //        toItem: nil,
        //        attribute: .NotAnAttribute,
        //        multiplier: 1.0,
        //        constant: webView.scrollView.contentSize.height
        //      )
        //    )
        //    webView.layoutIfNeeded()
        //    if serviceItemForLoading?.type == "software" {
        //      webView.scalesPageToFit = true
        //      webView.hidden = false
        //    } else {
        //    countOfResize += 1
        //    }
        self.loadingIndicator?.stopAnimating()
    }
    
    //
    //  func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    //    guard serviceItemForLoading?.type == "software" else { return false }
    //    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.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 containToken
    //  }
    //
    //  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 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)")
        AlertViewUtil.showAlert(error.localizedDescription)
        self.loadingIndicator?.stopAnimating()
        //    debugPrint("didFailLoadWithError")
    }
}

