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

import Foundation
import UIKit

class StepViewController : ScrolledViewController, UIAlertViewDelegate, UIPickerViewDelegate {
    
    @IBOutlet var helpButton: HelpButton!
    
    var stepNumber = 0
    
    static var regions: [CallbackRegion] = []
    static var regionNames: [String] = []
    
    var selectedRegion: CallbackRegion?
    var cityButton: UIButton!
    
    @IBAction func helpClicked(sender: UIButton) {
        self.view.endEditing(true)
        if StepViewController.regions.isEmpty {
            SpinneredAlert.show(self)
            Facade.sharedInstance().getOfferRegions({ (callbackRegions) in
                StepViewController.regions = callbackRegions
                StepViewController.regionNames = callbackRegions.map({$0.name ?? ""})
                self.selectedRegion = StepViewController.regions[0]
                self.dismissViewControllerAnimated(true, completion: nil)
                self.showHelpAlert()
                }, onError: { (error) in
                    
            }) {
                
            }
        } else {
            self.showHelpAlert()
        }
    }
    
    func cityButton_touchUpInside(sender: UIButton) {
        let acp = ActionSheetMultipleStringPicker(title: "", rows: [StepViewController.regionNames], initialSelection: [0], doneBlock: {
            picker, values, indexes in
            print("values = \(values)")
            print("indexes = \(indexes)")
            dispatch_async(dispatch_get_main_queue()){
                self.selectedRegion = StepViewController.regions[values[0] as! Int]
                self.cityButton.setTitle(StepViewController.regions[values[0] as! Int].name ?? "", forState: .Normal)
            }
            return
            }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: sender)
        
        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()
    }
    
    func showHelpAlert() {
        
        let customAlertVC = CustomAlertViewController.fromStoryboard()
        customAlertVC.fillAndShowAlert(300, height: 300, presentingVC: self, closure: { (alertVC) -> Void in
            
            customAlertVC.addTitleAndMessage(LS("registration.label.need_help"), msg: LS("registration.label.we_recall"))
            customAlertVC.addButtonTitles(rightButtonTitle: LS("registration.button.send"))
            
            for i in 0..<2 {
                
                let textField = alertVC.createTextField()
                var localizedId = ""
                switch i {
                case 0:
                    localizedId = "FIO"
                    break
                case 1:
                    localizedId = "phone_number"
                    textField.text = "+7 "
                    break
                default:
                    break
                }
                textField.localizeWithParent(self, localizedId: localizedId)
                customAlertVC.addTextField(textField)
            }
            
            KeyboardUtil.changeKeyboardType(UIKeyboardType.NumberPad, textField: alertVC.textFields[1])
            self.cityButton = UIButton(frame: CGRect(origin: CGPointZero, size: CGSize.zero))
            self.cityButton.setTitle(self.selectedRegion?.name ?? "", forState: .Normal)
            self.cityButton.setTitleColor(Color.BlueButtonColor, forState: .Normal)
            self.cityButton.addTarget(self, action: #selector(StepViewController.cityButton_touchUpInside(_:)), forControlEvents: .TouchUpInside)
            self.cityButton.sizeToFit()
            
            alertVC.textFields[1].tag = 101
            
            customAlertVC.addView(self.cityButton)
            customAlertVC.addButtonHandlers({ (button) -> Void in
                
                }, rightButtonHandler: { (button) -> Void in
                    let fioTitle = alertVC.textFields[0].text
                    let phoneNumberTitle = getPhoneDigits(alertVC.textFields[1].text!)
        
                    if fioTitle == "" || phoneNumberTitle == "" || self.selectedRegion == nil {
                        AlertViewUtil.showIncorrectAlert()
                    } else if containsLetters(phoneNumberTitle) || phoneNumberTitle.characters.count != 10 {
                        AlertViewUtil.showAlert(LS("registration.label.check_phone_number"))
                    } else {
                        let params:[String: AnyObject] = ["region": self.selectedRegion!.id!,
                            "phone": phoneNumberTitle,
                            "type": 1,
                            "form_type": 1,
                            "name": fioTitle!,
                            "region_type": self.selectedRegion!.regionType!
                        ]
                        PKNotification.loading(true)
                        Facade.sharedInstance().callbackSend(params, onSuccess: { (msg) in
                            AlertViewUtil.showAlert(msg)
                            }, onError: { (error) in
                                AlertViewUtil.showAlert(error)
                            }, onFinish: {
                                PKNotification.loading(false)
                        })
                    }
            })
        })
        
    }
    
    internal func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        print("index: \(buttonIndex)")
    }
    
//    override func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
//        let textFieldText: NSString = textField.text ?? ""
//        let txtAfterUpdate = textFieldText.stringByReplacingCharactersInRange(range, withString: string)
//        
//        if ( textField.tag == 101 ) {
//            setPhoneNumber(getFormattedPhone(txtAfterUpdate))
//            return false
//        } else {
//            return true
//        }
//    }
//    
//    func setPhoneNumber(phone: String) {
//        alertVC.textFields[0].text = phone
//    }
    
}

extension StepViewController {
    override var localizedId: String {
        return "registration"
    }
}
