//
//  UIFastPayViewController.swift
//  kt
//
//  Created by Admin on 18.12.16.
//  Copyright © 2016 SimpleCode. All rights reserved.
//

import Foundation

class UIFastPayViewController : ViewControllerWithMenu, UITableViewDelegate {
    
    //MARK: - IBOutlet
    @IBOutlet weak var tableView: UITableView!
    
    //MARK: - Variables
    var cellsData : [FastPayCellData] = []
    
    //MARK: - System functions
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.title = LS("menu.fastPay")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createCellsData()
        
        configureNavigationBar()
        tableView.reloadData()
        addMenuBarButton()
        
    }
    
    override func viewWillAppear(animated: Bool) {
        createCellsData()
        tableView.reloadData()
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        switch segue.identifier! {
        case "createPayIdentifier":
            let vc = segue.destinationViewController as! UICreateFastPayViewController
            
            if (sender != nil) {
                vc.fastPayForEditing = sender as! FastPayItem
            }
            break
        default:
            break
        }
        
        
    }
    
    //MARK: - Private functions
    
    private func configureNavigationBar() {
        configureBlueNavbar()
        addBackButtonForDefault(.whiteColor())
        let barButtonItem = UIBarButtonItem(title: LS("fastPay_create_button_createTitle"), style: .Plain, target: self, action: #selector(showAddingFastPayForm))
        barButtonItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFontOfSize(17), NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Normal)
        self.navigationItem.rightBarButtonItem = barButtonItem
    }
    
    override func configureBlueNavbar() {
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        self.navigationController?.navigationBar.barTintColor = Color.DashboardBlueColor
        self.navigationController?.navigationBar.barStyle = UIBarStyle.Black
        self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
        navigationController?.navigationBar.setBottomBorderColor(UIColor.whiteColor(), height: 0)
        self.navigationController?.navigationBar.translucent = false
        self.navigationItem.titleView?.tintColor = UIColor.whiteColor()
        self.navigationController?.WhiteLabel()
    }
    
    @objc private func showAddingFastPayForm() {
        performSegueWithIdentifier("createPayIdentifier", sender: nil)
    }
    
    private func createCellsData() {
        cellsData = []
        let items = FastPayManager.sharedInstance().getStoredFastPays()
        for fastPay in items {
            
            let cellData = getFastPayCellData(fastPay)
            cellData.fastPayItem = fastPay
            cellData.onClick = {
                self.showEditForm(cellData.fastPayItem!)
            }
            cellData.onPayClick = { (item) in
                self.showPayForm(item)
            }
            cellsData.append(cellData)
        }
        
        if ( items.isEmpty ) {
            dispatch_async(dispatch_get_main_queue()) {
                let noDataLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: self.tableView.bounds.size.height))
                noDataLabel.text = LS("no_data")
                self.tableView.backgroundView  = noDataLabel
                noDataLabel.textAlignment = NSTextAlignment.Center
                self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
            }
        } else {
            self.tableView.backgroundView = nil
        }
        
    }
    
    private func getFastPayCellData(fastPay: FastPayItem) -> FastPayCellData {
        if ( fastPay.isPhoneNumber() ) {
            return FastPayCellData(name: fastPay.title, phoneNumber: fastPay.phoneNumber, credit: "")
        }
        else {
            return FastPayCellData(name: fastPay.title, guid: fastPay.guid, credit: "")
        }
    }
    
    private func showEditForm(fastPay : FastPayItem) {
        performSegueWithIdentifier("createPayIdentifier", sender: fastPay)
    }
    
    private func showPayForm(cellData : FastPayCellData) {
        
        if ( cellData.fastPayItem!.isPhoneNumber() ) {
            sendOnlinePaymentRequestPhoneNumber(cellData.phoneNumberValue, summ: cellData.summ)
        } else {
            sendOnlinePaymentRequestAccountNumber(cellData.accountNumberValue, summ: cellData.summ)
        }
    }
    
    private func sendOnlinePaymentRequestPhoneNumber(phoneNumber : String, summ: String) {
        let request = PaymentCreateOrderRequest(payType: "phone", email: AbonentInfoManager.sharedInstance.abonentInfo?.email, guidOrPhone: phoneNumber, amount: summ, lang: AppLocalization.language().forTelecom)
        requestExecute(request)
        
    }
    
    private func sendOnlinePaymentRequestAccountNumber(accountNumber : String, summ: String) {
        let request = PaymentCreateOrderRequest(payType: "guid", email: AbonentInfoManager.sharedInstance.abonentInfo?.email, guidOrPhone: accountNumber, amount: summ, lang: AppLocalization.language().forTelecom)
        requestExecute(request)
    }
    
    func requestExecute(request : PaymentCreateOrderRequest ) {
        guard request.validateFields() else { AlertViewUtil.showAlert(request.validationMessage); return }
        self.processRequest(true)
        Facade.sharedInstance().createOrder(request.params, onSuccess: { (data) in
            let vc = self.storyboard!.instantiateViewControllerWithIdentifier("onlinePaymentStoryboardId") as! OnlinePaymentFormViewController
            vc.data = data
            self.navigationController?.showViewController(vc, sender: nil)
            //self.presentViewController(vc, animated: true, completion: nil)
            }, onError: { (error) in
                AlertViewUtil.showIncorrectAlert(error)
            }, onFinish: {
                self.processRequest(false)
        })
    }
    
    //MARK: - IBOutlets
    
    
}

//MARK: UITableViewDataSource
extension UIFastPayViewController {
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellData = cellsData[indexPath.row]
        let cell = tableView.dequeueReusableCellWithIdentifier(cellData.cellType.reuseIdentifier, forIndexPath: indexPath) as! UIFastPayTableViewCell
        cell.selectionStyle = .None
        cell.fillWithCellData(cellData)
        return cell
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return cellsData.count
    }
}

//MARK: UITableViewDelegate
extension UIFastPayViewController {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        cell?.selected = false
        let cellData = cellsData[indexPath.row]
        cellData.onClick()
    }
    
}
