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

import UIKit

class SettingsViewController : ViewControllerWithMenu, UITableViewDataSource, UITableViewDelegate {
    
    private var language = AppLocalization.language()
    private var city = NSUserDefaults.standardUserDefaults().integerForKey(UserDefaultsCity)
    
    private var cities = CitiesManager.sharedInstance().getCities().sort { $0.id < $1.id }
    
    @IBOutlet private weak var _tableView: UITableView!
    
    // MARK : View lifi cicle
    
    override func viewDidLoad() {
        self.navigationItem.title = LocalizedString("menu.settings", description: "Настройки")
        super.viewDidLoad()
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(SettingsViewController.reloadCities), name: FacadeUpdateCities, object: nil)
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        configureBlueNavbar()
    }
    
    func reloadCities() {
        cities = CitiesManager.sharedInstance().getCities().sort { $0.id < $1.id }
        _tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: .Automatic)
    }
    
    // MARK : UITableViewDataSource
    
    private let cellIdentifier = "settingCell"
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
//            return 3
            return 0
        case 1:
            return cities.count
        default:
            assert(true, "settingsVC section amount more than 2")
        }
        return 3
    }
    
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        let text = section == 0 ? LS("mainSettings_sectionTitle_language") : LS("mainSettings_sectionTitle_cities")
        return text
    }
    
    /*func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
     /*let text = section == 0 ? LS("mainSettings_sectionTitle_language") : LS("mainSettings_sectionTitle_cities")
     let view = UIView(frame:CGRect(x: 0, y: section == 1 ? -6 : 0, width: tableView.frame.size.width, height: 26))
     view.backgroundColor = UIColor(red: 247.0 / 255.0, green: 247.0 / 255.0, blue: 247.0 / 255.0, alpha: 1.0)
     let textLabel = UILabel(frame: CGRect(x: 14, y: section == 0 ? 0 : 0, width: 300, height: 20))
     textLabel.textColor = UIColor.blackColor()
     textLabel.font = UIFont(name: "PTSans-Regular", size: 20)
     textLabel.text = text
     view.addSubview(textLabel)*/
     let view = UIView(frame:CGRect(x: 0, y: -10, width: 100, height: 100))
     view.backgroundColor = UIColor.redColor()
     
     return view
     }*/
    
    
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return section == 0 ? 28 : 26
    }
    
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as UITableViewCell
        
        switch indexPath.section {
        case 0:
            if languageToIndex(language) == indexPath.row {
                cell.accessoryType = .Checkmark
            }
            else {
                cell.accessoryType = .None
            }
            break
        case 1:
            if city == cities[indexPath.row].id {
                cell.accessoryType = .Checkmark
            }
            else {
                cell.accessoryType = .None
            }
            break
        default:
            assert(true, "settingsVC section amount more than 2")
            break
        }
        
        switch (indexPath.section, indexPath.row) {
        case (0, 0):
            cell.textLabel!.text = LocalizedString("lang_en", description: "English")
            break
        case (0, 1):
            cell.textLabel!.text = LocalizedString("lang_ru", description: "Русский")
            break
        case (0, 2):
            cell.textLabel!.text = LocalizedString("lang_kz", description: "Kazakh")
            break
        case (1, _):
            cell.textLabel!.text = cities[indexPath.row].name
            break
        default:
            assert(true, "settingsVC section amount more than 2")
            break
        }
        //cell.selectionStyle = .None
        //cell.backgroundColor = UIColor.yellowColor()
        return cell
    }
    
    // MARK: UITableViewDelegate
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        
        var cellForUnselect : UITableViewCell?
        
        switch indexPath.section {
        case 0:
            cellForUnselect = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: languageToIndex(language), inSection: 0))
            break
        case 1:
            if let cityIndex = cities.indexOf({$0.id == self.city}) {
                cellForUnselect = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: cityIndex, inSection: 1))
            }
            break
        default:
            assert(true, "settingsVC section amount more than 2")
            break
        }
        
        cellForUnselect?.accessoryType = .None
        
        switch indexPath.section {
        case 0:
            switch indexPath.row {
            case 0:
                language = .English
                break
            case 1:
                language = .Russian
                break
            case 2:
                language = .Kazakh
                break
            default:
                assert(true, "settingsVC 0 section row amount more than 3")
                break
            }
            if AppLocalization.language() != language {
                AppLocalization.setLanguage(language)
                self.navigationItem.title = LocalizedString("menu.settings", description: "Настройки")
                PKNotification.loading(true)
                self.enableView(false)
                Facade.sharedInstance().getCities({ (error) in
                    DynamicMenuManager.sharedInstance().getMenu({ error in
                        NSNotificationCenter.defaultCenter().postNotificationName("ReloadTable", object: nil)
                        PKNotification.loading(false)
                        self.enableView(true)
                        if let error = error {
                            AlertViewUtil.showErrorAlert(LS("error"), message: error)
                        } else {
                        }
                    })
                })
            }
            break
        case 1:
            city = cities[indexPath.row].id
            NSUserDefaults.standardUserDefaults().setInteger(cities[indexPath.row].id, forKey: UserDefaultsCity)
            break
        default:
            assert(true, "settingsVC section amount more than 2")
            break
        }
        
        NSUserDefaults.standardUserDefaults().synchronize()
        
        let cell = tableView.cellForRowAtIndexPath(indexPath)!
        cell.accessoryType = .Checkmark
    }
    
    private func enableView(enable: Bool) {
        //    view.userInteractionEnabled = !enable
        self.navigationItem.leftBarButtonItem?.enabled = enable
    }
    
    // MARK: Helper
    
    func languageToIndex(language: Language) -> Int {
        switch language {
        case .English:
            return 0
        case .Russian:
            return 1
        case .Kazakh:
            return 2
        }
    }
    
}
