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

import Foundation
import UIKit

class OfferFormLinkCell : UITableViewCell {
  @IBOutlet weak var agreementLabel: UILabel!
  @IBOutlet weak var linkButton: UIButton!
  @IBOutlet weak var checkButton: NextButton!
  var vc: OfferFormViewController?
  var pay_touchUpInside: (() -> Void)?
  
  override func awakeFromNib() {
    super.awakeFromNib()
    checkButton.backgroundColor = Color.DashboardBlueColor
    localizeSubviews()
  }
  
  func fillCell(vc: OfferFormViewController) {
    self.vc = vc
  }

  private func localizeSubviews() {
    linkButton.setTitle((LS("offer_form.button.dont_have_address")).uppercaseString, forState: .Normal)
    agreementLabel.localizeWithParent(self, localizedId: "agreement")
    checkButton.setTitle(LS("offer_form.button.check"), forState: .Normal)
  }
  
  private func loading(enabled: Bool) {
    self.vc!.view.userInteractionEnabled = !enabled
    PKNotification.loading(enabled)
  }
  
  func fillCache() {
    OffersManager.sharedInstance().pointType = self.vc!.pointType
    OffersManager.sharedInstance().cityId = self.vc!.cityId
    OffersManager.sharedInstance().regionId = self.vc!.regionId
    OffersManager.sharedInstance().areaId = self.vc!.areaId
    OffersManager.sharedInstance().villageId = self.vc!.villageId
    OffersManager.sharedInstance().streetId = self.vc!.streetId
    OffersManager.sharedInstance().houseId = self.vc!.houseId
  }
  
  @IBAction func checkButton_touchUpInside(sender: NextButton) {
    let request = GetSpecialOffersRequest(portal_city_id: "\(CitiesManager.sharedInstance().userCity().id)", service_type: "1", type: vc!.pointType, house: vc!.houseId)
    if request.validateFields() {
      fillCache()
      self.loading(true)
      Facade.sharedInstance().getSpecialOffers(request.params, onSuccess: { (specialOffers) in
        self.vc!.performSegueWithIdentifier("showOffers", sender: specialOffers)
        }, onError: { (error) in
          AlertViewUtil.showErrorAlert(message: error)
        }, onFinish: {
          self.loading(false)
      })
    } else {
      AlertViewUtil.showIncorrectAlert(LS("offer_form.label.fill_form_fully"))
    }
  }
  
  @IBAction func linkButton_touchUpInside(sender: UIButton) {
    vc!.performSegueWithIdentifier("callback", sender: nil)
  }
  
}

extension OfferFormLinkCell: LocalizedParent {
  var localizedId: String {
    return "offer_form"
  }
}
