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

import Foundation
import UIKit

class AccessRecoveryViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate {
    
    @IBOutlet var fourthButton: ButtonWithTopAndBottomBorders!
    @IBOutlet var thirdButton: ButtonWithTopAndBottomBorders!
    @IBOutlet var secondButton: ButtonWithTopAndBottomBorders!
    @IBOutlet var firstButton: ButtonWithTopAndBottomBorders!
    @IBOutlet var tableView: UITableView!
    let reuseCellIdentifier = "cell"
    var items = AccessRecoveryViewController.generateItems()
    let cancelTitle = §"cancel"
    let sendButton = §"login.alert.send"
    
    static func generateItems() -> [String] {
        return [§"login.passsword_restoration.email",
                §"login.alert.email.message",
                §"login.passsword_restoration.account",
                §"login.passsword_restoration.phone_number"]
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        print("buttonIndex: \(buttonIndex)")
    }
    
    @IBAction func withEmail_touchUpInside(sender: ButtonWithTopAndBottomBorders) {
        generateRecoverAlert("email")
    }
    
    func forgetPasswordSend(params: [String: AnyObject]) {
        Facade.sharedInstance().forgetPassword(params, onError: { error -> Void in
            let alert = UIAlertView(title: §"error", message: error, delegate: self, cancelButtonTitle: "OK")
            alert.tintColor = self.view.tintColor
            alert.backgroundColor = UIColor.whiteColor()
            alert.alpha = 1
            alert.show()
            PKNotification.loading(false)
            }, onSuccess: { () -> Void in
                let alert = UIAlertView(title: "Успех", message: nil, delegate: self, cancelButtonTitle: "OK")
                alert.tintColor = self.view.tintColor
                alert.backgroundColor = UIColor.whiteColor()
                alert.alpha = 1
                alert.show()
                PKNotification.loading(false)
        })
    }
    
    func generateRecoverAlert(recoverType: String) {
        var alertTitle = ""
        var alertMessage = ""
        if recoverType == "email" {
            alertTitle = §"login.passsword_restoration.email"
            alertMessage = §"login.alert.email.message"
        } else if recoverType == "guid" {
            alertTitle = §"login.passsword_restoration.account"
            alertMessage = "todo: recover by account number text"
        } else if recoverType == "phone" {
            alertTitle = §"login.passsword_restoration.phone_number"
            alertMessage = "todo: recover by phone number text"
        }
        let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addTextFieldWithConfigurationHandler { (textField) -> Void in
            
        }
        alertController.addAction(UIAlertAction(title: cancelTitle, style: UIAlertActionStyle.Cancel, handler: nil))
        alertController.addAction(UIAlertAction(title: sendButton, style: UIAlertActionStyle.Default, handler: { (uiAlertActio) -> Void in
            if alertController.textFields?[0].text != "" {
                PKNotification.loading(true)
                let params = [
                    "type": recoverType,
                    "data": alertController.textFields![0].text!
                    ] as [String: AnyObject]
                self.forgetPasswordSend(params)
            }}
            )
        )
        self.presentViewController(alertController, animated: true, completion: nil)
    }
    
    @IBAction func withAccount_touchUpInside(sender: ButtonWithTopAndBottomBorders) {
        generateRecoverAlert("guid")
    }
    
    @IBAction func withPhone_touchUpInside(sender: ButtonWithTopAndBottomBorders) {
        generateRecoverAlert("phone")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        firstButton.setTitle(§"login.action_sheet.title", forState: UIControlState.Normal)
        secondButton.setTitle(§"login.passsword_restoration.email", forState: UIControlState.Normal)
        thirdButton.setTitle(§"login.passsword_restoration.account", forState: UIControlState.Normal)
        fourthButton.setTitle(§"login.passsword_restoration.phone_number", forState: UIControlState.Normal)
    }
}

//UITableViewDataSource
extension AccessRecoveryViewController {
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    // Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
    // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseCellIdentifier, forIndexPath: indexPath) as! AccessRecoveryCell
        cell.valueLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
        cell.valueLabel.numberOfLines = 0
        cell.layoutMargins = UIEdgeInsetsZero
        cell.preservesSuperviewLayoutMargins = false
        if indexPath.row == 0 {
            cell.valueLabel.font = UIFont(name: "PTSans-Regular", size: 14)
        } else {
            cell.valueLabel.font = UIFont(name: "PTSans-Bold", size: 17)
        }
        cell.valueLabel.text = items[indexPath.row]
        return cell
    }
}

//UITableViewDelegate
extension AccessRecoveryViewController {
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("clicked row: \(indexPath.row)")
    }
}
