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

import Foundation
import UIKit

class ProvidersViewController: ViewControllerWithMenu, UITableViewDataSource, UITableViewDelegate {
  @IBOutlet weak var pointsButton: UIButton!
  @IBOutlet weak var titleView: UIView!
  @IBOutlet weak var firstLabel: UILabel!
  @IBOutlet weak var secondLabel: UILabel!
  @IBOutlet weak var tableView: UITableView!
  let reuseCellIdentifier = "cell"
  var providersWrapper: ProvidersWrapper?
  var filteredProviders: [ProvidersWrapper.Provider] = [] {
    didSet {
      self.tableView.reloadData()
    }
  }
  var selectedIndexPath: NSIndexPath?
  var selectedLocationId: Int? {
    didSet {
      self.filteredProviders = filterByLocation(providersWrapper!.providers)
    }
  }
  
  @IBAction func points_touchUpInside(sender: UIButton) {
    if let providersWrapper = providersWrapper where !providersWrapper.cities.isEmpty {
      if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
        performSegueWithIdentifier("selectCityForIPad", sender: nil)
      } else {
        performSegueWithIdentifier("selectCity", sender: nil)
      }
    }
  }
  
  deinit {
    NSNotificationCenter.defaultCenter().removeObserver(self)
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    configureRightIndicator()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ProvidersViewController.getProviders),
                                                     name: AbonentInfoManager.NotificationNames.Update, object: AbonentInfoManager.sharedInstance)
    pointsButton.backgroundColor = Color.ServicePaymentAllProvidersBlueColor
    pointsButton.setTitleColor(Color.ServicesPaymentButtonTextColor, forState: .Highlighted)
    if AbonentInfoManager.sharedInstance.abonentInfo != nil {
      getProviders()
    } else {
      AbonentInfoManager.sharedInstance.updateUserInfo()
    }
  }
  
  func getProviders() {
    let request = GetProvidersRequest(accessToken: Facade.accessToken, clientId: Facade.clientId, serverId: Facade.serverId, abonentId: Facade.accountId)
    guard request.validateFields() else { return }
    loadingIndicator?.startAnimating()
    Facade.sharedInstance().getProviders(request.params, onSuccess: { (providersWrapper) in
      self.providersWrapper = providersWrapper
      self.filteredProviders = self.filterByLocation(self.providersWrapper!.providers)
      }, onError: { (error) in
        
      }, onFinish: {() in
        self.loadingIndicator?.stopAnimating()
    })
  }
  
  func configureNavbar() {
    loadingIndicator?.color = .whiteColor()
    configureBlueNavbar()
  }
  
  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    configureNavbar()
    localize()
    localizeSubviews()
  }
  
  private func localizeSubviews() {
    pointsButton.setTitle(LS("providers.label.all_points"), forState: .Normal)
    //    secondLabel.localizeWithParent(self, localizedId: "providers_note")
  }
  
  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    switch segue.identifier! {
    case "showPayment":
      let vc = segue.destinationViewController as! PaymentForProviderViewController
      vc.provider = providersWrapper?.providers[selectedIndexPath!.row]
      vc.providersWrapper = providersWrapper
      break
    case "selectCity":
      let nav = segue.destinationViewController as! UINavigationController
      let vc = nav.topViewController as! SelectCityForProviderViewController
      vc.vc = self
      break
    case "selectCityForIPad":
      let vc = segue.destinationViewController as! SelectCityForProviderViewController
      vc.vc = self
      break
    default:
      break
    }
    //    if segue.identifier == "showPayment" {
    //      let vc = segue.destinationViewController as! PaymentForProviderViewController
    //      vc.provider = providersWrapper?.providers[selectedIndexPath!.row]
    //      vc.providersWrapper = providersWrapper
    //    } else if segue.identifier == "selectCity" {
    //      let nav = segue.destinationViewController as! UINavigationController
    //      let vc = nav.topViewController as! SelectCityForProviderViewController
    //      vc.vc = self
    //    }
  }
}

// UITableViewDataSource
extension ProvidersViewController {
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredProviders.count
  }
  
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(reuseCellIdentifier, forIndexPath: indexPath) as! ProvidersPaymentCell
    cell.fillCell(filteredProviders[indexPath.row].name)
    //cell.selectionStyle = .None
    return cell
  }
  
  func filterByLocation(providersToFilter: [ProvidersWrapper.Provider]) -> [ProvidersWrapper.Provider] {
    guard let selectedLocationId = selectedLocationId where selectedLocationId != -1 else { return providersToFilter }
    return providersToFilter.filter({ (provider) -> Bool in
      return selectedLocationId == provider.locationId
    })
  }
}

// UITableViewDelegate
extension ProvidersViewController {
  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.selectedIndexPath = indexPath
    performSegueWithIdentifier("showPayment", sender: nil)
  }
}

extension ProvidersViewController {
  override var localizedId: String {
    return "providers"
  }
}
