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

import Foundation
import UIKit

enum ClaimCreationType {
  case RB
  case SC
}

enum ListBoxType : Int {
    case devices, damages, services, treatments
}

class RBCreationViewController: KeyboardedViewController, UITableViewDataSource, UITableViewDelegate, UIListBoxViewControllerDelegate {
  @IBOutlet weak var tableView: UITableView!
  weak var activeField: UITextField?
  var params: [String: AnyObject] = [String: AnyObject]()
  static let uneditableField = "uneditableField"
  static let fieldCell = "fieldCell"
  static let buttonCell = "buttonCell"
  let cells: [[String]] = [[RBCreationViewController.uneditableField, "device_number"],
                           [RBCreationViewController.uneditableField, "claim_type"],
                           [RBCreationViewController.fieldCell, "phone_or_comment"],
                           [RBCreationViewController.buttonCell, "create_rb"]]
  let scCells: [[String]] = [[RBCreationViewController.uneditableField, "device_number"],
                             [RBCreationViewController.uneditableField, "service"],
                             [RBCreationViewController.uneditableField, "treatment_type"],
                             [RBCreationViewController.fieldCell, "phone_or_comment"],
                             [RBCreationViewController.buttonCell, "create_rb"]]
  var selectedCells: [[String]] = []
  var claimListVC: ClaimListViewController!
  var selectedSiebelAccountData: SiebelAccount.SiebelAccountData? {
    didSet {
      tableView.reloadData()
    }
  }
  var damageSourceNamesList: [String] = []
  var damageSourceList: [DamageSource] = [] {
    didSet {
      tableView.reloadData()
    }
  }
  var currentDamageSource: DamageSource? {
    didSet {
      tableView.reloadData()
    }
  }
  var claimSourceList: [ClaimSource] = [] {
    didSet {
      tableView.reloadData()
    }
  }
  var claimSourceNamesList: [String] = []
  var claimSourceSubList: [ClaimSourceSub] = [] {
    didSet {
      tableView.reloadData()
    }
  }
  var claimSourceSubNamesList: [String] = []
  var currentClaimSource: ClaimSource! {
    didSet {
        requestClaimSubsources()
      tableView.reloadData()
      
    }
  }
  var currentClaimSubSource: ClaimSourceSub! {
    didSet {
      tableView.reloadData()
    }
  }
  var claimCreationType: ClaimCreationType!
  var vc : ClaimPageMenuViewController?

    
  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    configureBlueNavbar()
    addBackButtonForDefault(.whiteColor())
  }
  
  // MARK: Keyboard action
  func keyboardDidShow(notification: NSNotification) {
    let info = notification.userInfo!
    var kbRect = info[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue
    kbRect = view.convertRect(kbRect, fromView: nil)
    
    let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0,
                                     bottom:	kbRect.height, right: 0.0)
    tableView.contentInset = contentInsets
    tableView.scrollIndicatorInsets = contentInsets
    let aRect = view.frame
    if let textField = activeField	where !CGRectContainsPoint(aRect, textField.frame.origin) {
      tableView.scrollRectToVisible(textField.frame, animated: true)
    }
    tapGestureRecognizer.enabled = true
  }
  
  func keyboardWillBeHidden(notification: NSNotification) {
    let contentInsets = UIEdgeInsetsZero
    tableView.contentInset = contentInsets
    tableView.scrollIndicatorInsets = contentInsets
    resizeScrollViewToFitSubviews()
    tapGestureRecognizer.enabled = false
  }
  
  func resizeScrollViewToFitSubviews() {
    tableView.reloadData()
  }
  
  private func registerForKeyboardAction() {
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self, selector: #selector(RBCreationViewController.keyboardDidShow(_:)),
                                   name:UIKeyboardWillShowNotification, object: nil)
    notificationCenter.addObserver(self, selector: #selector(RBCreationViewController.keyboardWillBeHidden(_:)),
                                   name: UIKeyboardWillHideNotification, object: nil)
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    //    "claim_page_menu.label.create_repair_bureau" = "СОЗДАТЬ ЗАЯВКУ БР";
    //    "claim_page_menu.label.create_service_claims" = "СОЗДАТЬ СЕРВИСНОЕ ЗАЯВЛЕНИЯ";
    let titleLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 36))
    titleLabel.textColor = .whiteColor()
    titleLabel.font = UIFont.systemFontOfSize(15)
    titleLabel.textAlignment = .Center
    //    titleLabel.font = NavigationBarFont
    titleLabel.text = claimCreationType == .SC ? LS("claim_page_menu.label.create_service_claims") : LS("claim_page_menu.label.create_repair_bureau")
    //    title = claimCreationType == .SC ? LS("claim_page_menu.label.create_service_claims") : LS("claim_page_menu.label.create_repair_bureau")
    //navigationItem.titleView = titleLabel
    self.title = titleLabel.text
    configureTableView()
    tableView.addGestureRecognizer(tapGestureRecognizer)
    registerForKeyboardAction()
    if claimCreationType == .RB {
      selectedCells = cells
    } else {
      selectedCells = scCells
    }
    requestData()
  }
  
  func requestData() {
    if !self.claimListVC.siebelAccount.siebelAccountDataList.isEmpty {
      selectedSiebelAccountData = self.claimListVC.siebelAccount.siebelAccountDataList[(self.vc?.selectedSiebelAccountDataIndex)!]//self.vc?.selectedSiebelAccountData//self.claimListVC.siebelAccount.siebelAccountDataList[0]
    }
    if claimCreationType == .RB {
      requestDamageSourceList()
    } else {
        requestDamageSourceList()
        requestClaimSources()
    }
  }
  
  func requestClaimSources() {
    let request = GetProvidersRequest(accessToken: Facade.accessToken, clientId: Facade.clientId, serverId: Facade.serverId, abonentId: Facade.accountId)
    if request.validateFields() {
      self.processRequest(true)
      Facade.sharedInstance().getClaimSourceList(request.params, onSuccess: { (claimSourceList) in
        self.processRequest(false)
        self.claimSourceList = claimSourceList
        self.claimSourceNamesList = claimSourceList.map {$0.typeName ?? ""}
        if !claimSourceList.isEmpty {
          self.currentClaimSource = claimSourceList[0]
        }
        }, onError: { (error) in
            self.processRequest(false)
          AlertViewUtil.showMessageAlert(error, vc: self)
            
      }) {
        
      }
    }
  }
  
  func requestClaimSubsources() {
    let params: [String: AnyObject] = ["access_token": Facade.accessToken!,
                                       "client_id": Facade.clientId!,
                                       "server_id": Facade.serverId!,
                                       "abonent_id": Facade.accountId!,
                                       "type_name": currentClaimSource.typeName!,
                                       "type_id": currentClaimSource.typeId!]
    self.processRequest(true)
    Facade.sharedInstance().getClaimSourceSubList(params, onSuccess: { (claimSourceSubList) in
      self.claimSourceSubList = claimSourceSubList
      self.claimSourceSubNamesList = claimSourceSubList.map {$0.subTypeValue ?? ""}
      if !self.claimSourceSubList.isEmpty {
        self.currentClaimSubSource = claimSourceSubList[0]
      }
      }, onError: { (error) in
        AlertViewUtil.showMessageAlert(error, vc: self)
    }) {
      self.processRequest(false)
    }
  }
  
  func requestDamageSourceList() {
    let request = GetProvidersRequest(accessToken: Facade.accessToken, clientId: Facade.clientId, serverId: Facade.serverId, abonentId: Facade.accountId)
    guard request.validateFields() else { return }
    self.processRequest(true)
    Facade.sharedInstance().getDamageSourceList(request.params, onSuccess: { (damageSourceList) in
      self.damageSourceList = damageSourceList
      self.damageSourceNamesList = damageSourceList.map({$0.comments ?? ""})
      if !damageSourceList.isEmpty {
        self.currentDamageSource = damageSourceList[0]
      }
      }, onError: { (error) in
        AlertViewUtil.showMessageAlert(error, vc: self)
    }) {
      self.processRequest(false)
    }
  }
  
  func closeWithCreatedItem() {
        self.vc!.reloadCurrentPage()
        self.back()
    }
    
  override func processRequest(enabled: Bool) {
        super.processRequest(enabled)
        self.navigationItem.leftBarButtonItem?.enabled = !enabled
        self.view.userInteractionEnabled = !enabled
        self.vc?.view.userInteractionEnabled = !enabled
    }
    
  private func configureTableView() {
    tableView.estimatedRowHeight = 150
    tableView.rowHeight = UITableViewAutomaticDimension
  }
    
    func processingSelectionDevices(index : Int) {
        self.vc?.selectedSiebelAccountDataIndex = index
        let currentAccountNumber = self.selectedSiebelAccountData?.assetId
        let newAccountNumber = (self.claimListVC.siebelAccount.siebelAccountDataList[index]).assetId
        if (newAccountNumber!.compare(currentAccountNumber!) != NSComparisonResult.OrderedSame) {
            self.selectedSiebelAccountData = self.claimListVC.siebelAccount.siebelAccountDataList[index]
        }
    }
    
    func processingSelectionDamages(index : Int) {
        guard !damageSourceNamesList.isEmpty else { return }
        let a = self.currentDamageSource?.id
        let b = self.damageSourceList[index].id
        if (a?.compare(b!) != NSComparisonResult.OrderedSame) {
            self.currentDamageSource = self.damageSourceList[index]
        }
    }
    
    func processingSelectionServices(index : Int) {
        guard !self.claimSourceNamesList.isEmpty else { return }
        dispatch_async(dispatch_get_main_queue()){
            let a = self.currentClaimSource.typeValue
            let b = self.claimSourceList[index].typeValue
            if (a?.compare(b!) != NSComparisonResult.OrderedSame) {
                self.currentClaimSource = self.claimSourceList[index]
            }
        }
    }
    
    func processingSelectionTreatmentType(index : Int) {
        guard !self.claimSourceSubNamesList.isEmpty else { return }
        dispatch_async(dispatch_get_main_queue()){
            let a = self.currentClaimSubSource.subTypeValue
            let b = self.claimSourceSubList[index].subTypeValue
            if (a?.compare(b!) != NSComparisonResult.OrderedSame) {
                self.currentClaimSubSource = self.claimSourceSubList[index]
            }
        }
    }
        
    func showDamageList() {
        let vc = storyboard?.instantiateViewControllerWithIdentifier("listBoxViewControllerIdentifier") as! UIListBoxViewController
        vc.listBoxItems = self.damageSourceList
        vc.title = LS("claim_page_menu.label.claim_type")
        vc.delegate = self
        vc.tag = ListBoxType.damages.rawValue
        showViewController(vc, sender: self)
    }
    
    func showSelectDevices() {
        let vc = storyboard?.instantiateViewControllerWithIdentifier("listBoxViewControllerIdentifier") as! UIListBoxViewController
        vc.listBoxItems = claimListVC.siebelAccount.siebelAccountDataList
        vc.title = LS("claim_page_menu.cell.deviceId_title")
        vc.delegate = self
        vc.tag = ListBoxType.devices.rawValue
        showViewController(vc, sender: self)
    }
  
    func showSelectService() {
        guard !self.claimSourceNamesList.isEmpty else { return }
        let vc = storyboard?.instantiateViewControllerWithIdentifier("listBoxViewControllerIdentifier") as! UIListBoxViewController
        vc.listBoxItems = claimSourceList
        vc.title = LS("claim_page_menu.label.service")
        vc.delegate = self
        vc.tag = ListBoxType.services.rawValue
        showViewController(vc, sender: self)
    }
    
    func showSelectTreatmentType() {
        guard !self.claimSourceSubNamesList.isEmpty else { return }
        let vc = storyboard?.instantiateViewControllerWithIdentifier("listBoxViewControllerIdentifier") as! UIListBoxViewController
        vc.listBoxItems = claimSourceSubList
        vc.title = LS("claim_page_menu.label.treatment_type")
        vc.delegate = self
        vc.tag = ListBoxType.treatments.rawValue
        showViewController(vc, sender: self)
    }
    
}

//MARK: UIListBoxViewControllerDelegate
extension RBCreationViewController {
    
    func didSelectItem(listBoxViewController: UIListBoxViewController, selectedListBoxItem: ListBoxItemProtocol, numberIndex: NSNumber) {
        let index = numberIndex.integerValue
        switch listBoxViewController.tag {
        case ListBoxType.damages.rawValue:
            processingSelectionDamages(index)
            break
        case ListBoxType.devices.rawValue:
            processingSelectionDevices(index)
            break
        case ListBoxType.services.rawValue:
            processingSelectionServices(index)
            break
        case ListBoxType.treatments.rawValue:
            processingSelectionTreatmentType(index)
            break
        default:
            break
        }
    }
    
}

// UITableViewDelegate
extension RBCreationViewController {
    
  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let cell = tableView.cellForRowAtIndexPath(indexPath)
    cell?.selected = false
    if selectedCells[indexPath.row][0] == RBCreationViewController.uneditableField {
      switch selectedCells[indexPath.row][1] {
      case "device_number":
        //claimListVC.siebelAccountDataListNames
        //let rowsValues = claimListVC.siebelAccountDataListNames
        //claimListVC.siebelAccountDataListNames
        /*
        let rowsValues = claimListVC.siebelAccountDataListNames
        let item = ("\(claimListVC.currentSiebelAccountData?.assetNumber ?? "") \(claimListVC.currentSiebelAccountData?.deviceGroupName ?? "")").uppercaseString
        let indexOf = claimListVC.siebelAccountDataListNames.indexOf(item)
         
        let acp = ActionSheetMultipleStringPicker(title: "", rows: [rowsValues], initialSelection: [indexOf!], doneBlock: {
          picker, values, indexes in
            self.vc?.selectedSiebelAccountDataIndex = (values[0] as! NSNumber).integerValue
            if self.claimCreationType == .RB {
                self.requestDamageSourceList()
            } else {
                self.requestClaimSources()
            }

          dispatch_async(dispatch_get_main_queue()){
            let currentAccountNumber = self.selectedSiebelAccountData?.assetId
            let newAccountNumber = (self.claimListVC.siebelAccount.siebelAccountDataList[values[0] as! Int]).assetId
            if (newAccountNumber!.compare(currentAccountNumber!) != NSComparisonResult.OrderedSame) {
            self.selectedSiebelAccountData = self.claimListVC.siebelAccount.siebelAccountDataList[values[0] as! Int]
            }
          }
          return
          }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: cell)
        //acp.setf
        acp.setDoneButton(UIBarButtonItem(title: LS("ok"), style: .Plain, target: self, action: Selector()))
        acp.setCancelButton(UIBarButtonItem(title: LS("cancel"), style: .Plain, target: nil, action: Selector()))
        acp.showActionSheetPicker()*/
        showSelectDevices()
        break
      case "claim_type":
        showDamageList() /*
        guard !damageSourceNamesList.isEmpty else { return }
        let acp = ActionSheetMultipleStringPicker(title: "", rows: [self.damageSourceNamesList], initialSelection: [self.currentDamageSource == nil ? 0 : self.damageSourceList.indexOf({$0.id == self.currentDamageSource!.id})!], doneBlock: {
          picker, values, indexes in
          dispatch_async(dispatch_get_main_queue()){
            let a = self.currentDamageSource?.id
            let b = self.damageSourceList[values[0] as! Int].id
            if (a?.compare(b!) != NSComparisonResult.OrderedSame) {
            self.currentDamageSource = self.damageSourceList[values[0] as! Int]
            }
          }
          return
          }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: cell)
        
        acp.setDoneButton(UIBarButtonItem(title: LS("ok"), style: .Plain, target: self, action: Selector()))
        acp.setCancelButton(UIBarButtonItem(title: LS("cancel"), style: .Plain, target: nil, action: Selector()))
        acp.showActionSheetPicker() */
        break
      case "service":
        showSelectService()
        /*guard !self.claimSourceNamesList.isEmpty else { return }
        let acp = ActionSheetMultipleStringPicker(title: "", rows: [self.claimSourceNamesList], initialSelection: [self.currentClaimSource == nil ? 0 : self.claimSourceList.indexOf({self.currentClaimSource!.typeId == $0.typeId})!], doneBlock: {
          picker, values, indexes in
          //        values[0]
          dispatch_async(dispatch_get_main_queue()){
            let a = self.currentClaimSource.typeValue
            let b = self.claimSourceList[values[0] as! Int].typeValue
            if (a?.compare(b!) != NSComparisonResult.OrderedSame) {
            self.currentClaimSource = self.claimSourceList[values[0] as! Int]
            }
          }
          return
          }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: cell)
        
        acp.setDoneButton(UIBarButtonItem(title: LS("ok"), style: .Plain, target: self, action: Selector()))
        acp.setCancelButton(UIBarButtonItem(title: LS("cancel"), style: .Plain, target: nil, action: Selector()))
        acp.showActionSheetPicker()*/
        break
      case "treatment_type":
        showSelectTreatmentType()
        /*guard !self.claimSourceSubNamesList.isEmpty else { return }
        let acp = ActionSheetMultipleStringPicker(title: "", rows: [self.claimSourceSubNamesList], initialSelection: [self.currentClaimSubSource == nil ? 0 : self.claimSourceSubList.indexOf({$0.subTypeId == self.currentClaimSubSource!.subTypeId})!], doneBlock: {
          picker, values, indexes in
          //        values[0]
          dispatch_async(dispatch_get_main_queue()){
            let a = self.currentClaimSource.typeValue
            let b = self.claimSourceList[values[0] as! Int].typeValue
            if (a?.compare(b!) != NSComparisonResult.OrderedSame) {
            self.currentClaimSubSource = self.claimSourceSubList[values[0] as! Int]
            }
          }
          return
          }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: cell)
        
        acp.setDoneButton(UIBarButtonItem(title: LS("ok"), style: .Plain, target: self, action: Selector()))
        acp.setCancelButton(UIBarButtonItem(title: LS("cancel"), style: .Plain, target: nil, action: Selector()))
        acp.showActionSheetPicker()*/
        break
      default:
        break
      }
    }
  }
    
}

// UITableViewDataSource
extension RBCreationViewController {
  
  func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    //    (cell as? RBCreationUneditableFieldTableCell)?.bottomLabel.setBottomBorder(Color.GrayTableCellSeparator)
    (cell as? RBCreationFieldTableCell)?.textField.setBottomBorder(Color.GrayTableCellSeparator)
  }
  
  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var resultCell = UITableViewCell()
    switch selectedCells[indexPath.row][0] {
    case RBCreationViewController.uneditableField:
      let cell = tableView.dequeueReusableCellWithIdentifier(selectedCells[indexPath.row][0], forIndexPath: indexPath) as! RBCreationUneditableFieldTableCell
      cell.fillCell(selectedCells[indexPath.row][1], vc: self)
      resultCell = cell
      break
    case RBCreationViewController.fieldCell:
      let cell = tableView.dequeueReusableCellWithIdentifier(selectedCells[indexPath.row][0], forIndexPath: indexPath) as! RBCreationFieldTableCell
      cell.fillCell(selectedCells[indexPath.row][1], vc: self)
      resultCell = cell
      break
    case RBCreationViewController.buttonCell:
      let cell = tableView.dequeueReusableCellWithIdentifier(selectedCells[indexPath.row][0], forIndexPath: indexPath) as! RBCreationButtonTableCell
      cell.fillCell(selectedCells[indexPath.row][1], vc: self)
      resultCell = cell
      break
    default:
      break
    }
    //resultCell.selectionStyle = .None
    if indexPath.row >= (cells.count - 2) {
        resultCell.separatorInset = UIEdgeInsets(top: 0, left: resultCell.bounds.size.width, bottom: 0, right: 0)
    }
    return resultCell
  }
  
  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return selectedCells.count
  }
    
}

extension RBCreationViewController {
  
  func textFieldDidBeginEditing(textField: UITextField) {
    textField.setBottomBorder(Color.BlueButtonColor)
    let cell: UITableViewCell?
    
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
      // Load resources for iOS 6.1 or earlier
      cell = textField.superview?.superview as? UITableViewCell
    } else {
      // Load resources for iOS 7 or later
      cell = textField.superview?.superview?.superview as? UITableViewCell
      // TextField -> UITableVieCellContentView -> (in iOS 7!)ScrollView -> Cell!
    }
    if let cell = cell {
      if let indexPath = tableView.indexPathForCell(cell) {
        tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: UITableViewScrollPosition.Top, animated: true)
      }
    }
  }
  
  func textFieldDidEndEditing(textField: UITextField) {
    textField.setBottomBorder(Color.GrayTableCellSeparator)
    activeField = nil
  }
  
}
