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

import Foundation
import UIKit

class ServicePaymentLinkCell : UITableViewCell {
  @IBOutlet weak var agreementLabel: UILabel!
  @IBOutlet weak var linkButton: UIButton!
  @IBOutlet weak var checkButton: NextButton!
  var vc: PaymentForProviderViewController!
  var pay_touchUpInside: (() -> Void)?
  
  override func awakeFromNib() {
    super.awakeFromNib()
    checkButton.backgroundColor = Color.DashboardBlueColor
    localizeSubviews()
  }
  
  private func validateForRegex() -> Bool {
    let contract = vc.contractNumber
    let regex = vc.provider!.contractregexp!
    return contract!.rangeOfString(regex, options: .RegularExpressionSearch) != nil
  }
  
  func fillCell(vc: PaymentForProviderViewController) {
    self.vc = vc
  }
  
  private func localizeSubviews() {
    checkButton.setTitle(LS("service_payment.button.pay"), forState: .Normal)
  }
  
  func loading(enabled: Bool) {
    PKNotification.loading(enabled)
    self.parentViewController?.view.userInteractionEnabled = !enabled
  }
  
  @IBAction func checkButton_touchUpInside(sender: NextButton) {
    let email = AbonentInfoManager.sharedInstance.abonentInfo?.email
    vc.fillVarsFromTextViews()
    
    let request = MythPostRequest(accessToken: Facade.accessToken, clientId: Facade.clientId, serverId: Facade.serverId, abonentId: Facade.accountId, email: email, session_pay_request: vc.providersWrapper?.sessionPayRequest, requestId: vc.providersWrapper?.requestId, provider: vc.provider?.parameter, phone: vc.contractNumber, amount: vc.amount, cardType: vc.selectedCardType?.name, bank: vc.selectedBank?.name)
    
    guard request.validateFields() else { AlertViewUtil.showAlert(LS("error_fill_all_fields")); return }
    guard validateForRegex() else { AlertViewUtil.showAlert(LS("service_payment.label.check_correctness")); return }
    loading(true)
    Facade.sharedInstance().mythPost(request.params, onSuccess: { (msg) in
      AlertViewUtil.showAlert(msg)
      }, onError: { (error) in
        AlertViewUtil.showErrorAlert(message: error)
      }, onFinish: {
        self.loading(false)
    })
  }
  
  @IBAction func linkButton_touchUpInside(sender: UIButton) {
    vc!.performSegueWithIdentifier("callback", sender: nil)
  }
  
}

extension ServicePaymentLinkCell: LocalizedParent {
  var localizedId: String {
    return "service_payment"
  }
}
