//
//  File.swift
//  kt
//
//  Created by Alexandr Zalutskiy on 16.01.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit

class MenuTableController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var abonentID: UILabel!
    @IBOutlet var topView: UIView!
    @IBOutlet var tableView: UITableView!
    
    var selectedIndexPath: NSIndexPath?
    
    let reuseCellIdentifier = "cell"
    
    let defaults = NSUserDefaults.standardUserDefaults()
    
    private let imagesNames = [
        "ic_home",
        "ic_business_center",
        "ic_assignment",
        "ic_credit_card",
        "ic_vpn_key",
        "ic_wifi",
        "ic_help_black",
        "ic_settings",
        "ic_exit_to_app"
    ]
    
    private var menuNames : [String]! = []
    
    func reloadData() {
        
        menuNames = [
            "Главная",
            "Все услуги",
            "Мои заявки",
            "Быстрая оплата",
            "Аренда ПО",
            "Точки Wi-Fi",
            "Помощь",
            "Настройки",
            "Выход"
        ]
        
    }
    
    func configureViews() {
        tableView.estimatedRowHeight = 60
        tableView.rowHeight = UITableViewAutomaticDimension
        topView.backgroundColor = Color.GrayTableCellSeparator
        self.view.backgroundColor = Color.GrayTableCellSeparator
        self.navigationController!.navigationBarHidden = true
    }
    
    func showSettings(sender:UITapGestureRecognizer) {
        let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
        let vc = storyBoard.instantiateViewControllerWithIdentifier("SettingsViewController") as! SettingsViewController
        self.navigationController?.presentViewController(vc, animated: true, completion: nil)
    }
    
    func registerObservers() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MenuTableController.reload), name: "LanguageChanged", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MenuTableController.reload), name: "ReloadTable", object: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        debugPrint("MenuTableController viewDidLoad begin")
        registerObservers()
        configureViews()
        debugPrint("MenuTableController viewDidLoad end")
    }
        
    override func viewWillAppear(animated: Bool) {
        
        super.viewWillAppear(animated)
        
        debugPrint("MenuTableController viewWillAppear begin")
        
        reloadData()
        
        tableView.reloadData()
        
        if let selectedIndexPath = selectedIndexPath {
            if selectedIndexPath.row < tableView.numberOfRowsInSection(selectedIndexPath.section) {
                tableView.selectRowAtIndexPath(selectedIndexPath, animated: false, scrollPosition: UITableViewScrollPosition.Middle)
            }
        }
        
        if let name = AbonentInfoManager.sharedInstance.abonentInfo?.name {
            nameLabel.text = name
        }
        
        if let abonent = Facade.accountId {
            abonentID.text = "Лицевой счет " + String(abonent)
        }
        
        debugPrint("MenuTableController viewWillAppear end")
    }
    
    func closeMenuAction(sender: UIButton) {
        let rvc = self.navigationController?.parentViewController as? RootVC
        rvc?.closeSideViewControllerAnimated(true, completion: nil)
    }
    
    func cabinetOpen(sender: AnyObject? = nil) {
        selectedIndexPath = nil
        let centerViewController = self.storyboard!.instantiateViewControllerWithIdentifier("MainViewController")
        if let pvc = self.navigationController?.parentViewController as? RootVC {
            pvc.presentCenterViewController(centerViewController, animated: true)
        }
    }
    
    func logOut() {
        selectedIndexPath = nil
        defaults.setValue("", forKey: "UserName")
        defaults.setValue("", forKey: "Password")
        defaults.setValue("", forKey: "AbonentName")
        Facade.expiresIn = nil
        Facade.serverId = nil
        Facade.accountId = nil
        Facade.clientId = nil
        Facade.accessToken = nil
        AbonentInfoManager.sharedInstance.abonentInfo = nil
        self.navigationController?.popToRootViewControllerAnimated(true)
        self.navigationController?.parentViewController?.navigationController?.popToRootViewControllerAnimated(true)
    }
    
    override func prefersStatusBarHidden() -> Bool {
        return true
    }
    
    override func preferredStatusBarUpdateAnimation() -> UIStatusBarAnimation {
        return .Slide
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func reload() {
        reloadData()
        tableView.reloadData()
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showService" {
            let nc = segue.destinationViewController as! ServiceNavigationController
            let vc = nc.topViewController as! ServiceListController
            vc.selectedIndex = selectedIndexPath!.row
        }
    }
}

// UITableViewDataSource
extension MenuTableController {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menuNames.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseCellIdentifier, forIndexPath: indexPath) as! MenuCell
        cell.fillCell(menuNames[indexPath.row], imageName: imagesNames[indexPath.row])
        return cell
    }
    
}

// UITableViewDelegate
extension MenuTableController {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        self.selectedIndexPath = indexPath
        
        var vc : UIViewController?
        
        switch indexPath.row {
        case 0:
            vc = storyboard!.instantiateViewControllerWithIdentifier(MainControllerId)
            break
        case 1:
            vc = storyboard!.instantiateViewControllerWithIdentifier(MainServiceControllerId)
            break
        case 2:
            vc = storyboard!.instantiateViewControllerWithIdentifier(ClaimControllerId)
            break
        case 3:
            vc = storyboard!.instantiateViewControllerWithIdentifier(FastPayControllerId)
            break
        case 4:
            vc = storyboard!.instantiateViewControllerWithIdentifier(SoftwareControllerId)
            break
        case 5:
            vc = storyboard!.instantiateViewControllerWithIdentifier(WiFiControllerId)
            break
        case 6:
            vc = storyboard!.instantiateViewControllerWithIdentifier("MainHelpViewController")
            break
        case 7:
            vc = storyboard!.instantiateViewControllerWithIdentifier("SettingsViewController")
            break
        case 8:
            logOut()
            break
        default:
            break
        }
        
        print(parentViewController)
        
        if let vc = vc {
            if let pvc = self.navigationController?.parentViewController as? RootVC {
                pvc.presentCenterViewController(vc, animated: true)
            }
        }
    }
}
