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

import UIKit

class ServiceListController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    // MARK: public variable
    var selectedIndex: Int!
    var data: [[String: AnyObject]]?
    var dataIndexes: [Int] = []
    var nestedAmount = 1
    var selectedIndexPath: NSIndexPath!
    var service : Service?
    //  var service : Service?
    
    // MARK: private const
    
    let cellIdentifier = "serviceCell"
    let notificationCenter = NSNotificationCenter.defaultCenter()
    let facade = Facade.sharedInstance()
    
    // MARK: Data
    
    private var servicesList: [ServiceItem] = []
    
    // MARK: UI
    
    @IBOutlet private weak var servicesTableView : UITableView!
    
    // MARK: View life cle
    
    override func viewWillAppear(animated: Bool) {
        configureBlueNavbar()
        super.viewWillAppear(animated)
        defineNestedLevel()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.data = (DynamicMenuManager.sharedInstance().menu[selectedIndex]["data"] as! [[String: AnyObject]])
        service = Service(rawValue: selectedIndex)
        if let serviceName = DynamicMenuManager.sharedInstance().menu[selectedIndex]["name"] as? String {
            self.navigationItem.title = serviceName
        }
        configureTableView()
        updateServicesList()
    }
    
//    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//        return 250
//    }
//    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//        return 250
//    }
    func configureTableView() {
        servicesTableView.estimatedRowHeight = 280
        servicesTableView.rowHeight = UITableViewAutomaticDimension
    }
//    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//        return 40
//    }
    
//    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        let headerView = UIView()
//        headerView.backgroundColor = UIColor.whiteColor()
//        return headerView
//    }
    
    private func updateServicesList() {
        servicesList = []
        for subItem in self.data! {
            if (subItem["data"] as? [[String: AnyObject]]) == nil {
                var url : String? = nil
                var description : String? = nil
                if let full = subItem["full"] {
                    url = full["seo_image"] as! String?
                    description = full["seo_description"] as! String!
                }
                //let url = subItem["full"]?["seo_image"] as! String?
                let serviceItem = ServiceItem(id: subItem["service_id"] as? Int, name: subItem["name"] as! String, key: subItem["key"] as? String, type: subItem["type"] as? String, imageUrlStr : url, description: description)
                servicesList.append(serviceItem)
                serviceItem.service = service;
            } else {
                let serviceItem = ServiceItem(name: subItem["name"] as! String, data: subItem["data"] as? [[String: AnyObject]])
                servicesList.append(serviceItem)
                serviceItem.service = service;
            }
        }
    }
    
    func exitFromNested() {
        if nestedAmount > 1 {
            nestedAmount -= 1
            self.data = DynamicMenuManager.sharedInstance().menu[selectedIndex]["data"] as! [[String: AnyObject]]
            self.dataIndexes.removeLast()
            if !self.dataIndexes.isEmpty {
                for dataIndex in dataIndexes {
                    self.data = self.data![dataIndex]["data"] as! [[String: AnyObject]]
                }
            }
            updateServicesList()
            self.servicesTableView.reloadData()
        } else {
            self.navigationController?.popViewControllerAnimated(true)
        }
        
    }
    
    func defineNestedLevel() {
        if nestedAmount > 1 {
            self.data = DynamicMenuManager.sharedInstance().menu[selectedIndex]["data"] as! [[String: AnyObject]]
            if !self.dataIndexes.isEmpty {
                for dataIndex in dataIndexes {
                    self.data = self.data![dataIndex]["data"] as! [[String: AnyObject]]
                }
            }
            updateServicesList()
            self.servicesTableView.reloadData()
        }
    }
    
    override func back() {
        exitFromNested()
    }
    
    // MARK: UITableViewDataSource
    
//    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
//        return 30
//    }
//    
//    func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
//        let view = UIView()
//        view.backgroundColor = UIColor.whiteColor()
//        return view
//    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1//servicesList.count
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return servicesList.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ServiceCell
        cell.setService(servicesList[indexPath.row], withRow: indexPath.row)
        //cell.selectionStyle = .None
        return cell
    }
    
    // MARK: UITableViewDelegate
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if let data = self.data, let nestedData = data[indexPath.row]["data"] as? [[String: AnyObject]] where !nestedData.isEmpty {
            nestedAmount += 1
            self.dataIndexes.append(indexPath.row)
            self.data = nestedData
            self.updateServicesList()
            self.servicesTableView.reloadData()
            addBackButtonForDefault(.whiteColor())
        } else {
            performSegueWithIdentifier("ShowServiceItemSegue", sender: nil)
        }
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    // MARK: Notifications
    
    func registerForServiceList() {
        notificationCenter.addObserver(
            self,
            selector: #selector(ServiceListController.setServicesItems(_:)),
            name: FacadeItemsSuccess,
            object: facade
        )
    }
    
    func unregisterForServiceList() {
        notificationCenter.removeObserver(
            self,
            name: FacadeItemsSuccess,
            object: facade
        )
    }
    
    // MARK: Facade observering
    
    func setServicesItems(notification: NSNotification) {
        unregisterForServiceList()
        servicesList = notification.userInfo!["items"] as! [ServiceItem]
        servicesTableView.reloadData()
    }
    
    // MARK: Navigation
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if (segue.identifier == Segue.ShowServiceItemSegue) {
            let index = servicesTableView.indexPathForSelectedRow!.row
            let vc = segue.destinationViewController as! ServiceItemScrollViewController
            //      vc.service = service
            vc.serviceItemForLoading = servicesList[index]
            SharedDataManager.sharedInstance().selectedServiceID = (vc.serviceItemForLoading?.id)
            //vc.loadView()
        }
    }
    
}
