//
//  CategoryPopUpController.swift
//  Vendoo
//
//  Created by Okechi Onyeje on 8/19/16.
//  Copyright © 2016 Okechi Onyeje. All rights reserved.
//

import UIKit

class CategoryPopUpController: UIViewController {
    @IBOutlet weak var table: UITableView!
    
    var categoryList: [Int: AnyObject] = Dictionary<Int, Dictionary<String,AnyObject>>()
    var parentCategory: [String] = []
    var ebayManager: EbayWebServiceManager!
    private var completion: ServiceResponse!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.table.delegate = self
        self.table.dataSource = self
        // Uncomment the following line to preserve selection between presentations
        

    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setManagers(ebayManager: EbayWebServiceManager){
        self.ebayManager = ebayManager
    }
    
    //@FIXME: Fix category selection for retrieving categories id values, hybrid categories don't work with this and have to manually add these
    func loadCategories( selectedCategory: String, selectedCatCompletion: ServiceResponse?) {
        self.parentCategory.append(selectedCategory)
        var catCode: String!
        
        if(self.parentCategory.count == 1) {
            var dict = EbayWebServiceManager.settingsDictionary["categories"] as! Dictionary<String, Dictionary<String, AnyObject>>
            var infoDict = dict[selectedCategory]!
            catCode = infoDict["cat_id"] as! String
            self.completion = selectedCatCompletion
        }else {
            for (index, catInfo) in self.categoryList {
                let level = Int(catInfo["level"] as! String)
                if(( level! == (self.parentCategory.count))) {
                    let name = catInfo["name"] as! String
                    if ((name == selectedCategory)){
                        catCode = catInfo["id"] as! String
                        break
                    }
                }
            }
        }
        
        self.categoryList = Dictionary<Int, AnyObject>()
        self.ebayManager.getSubCategories(selectedCategory, detailLevel: self.parentCategory.count + 1, catCode: catCode, onCompletion: {
            (dict, error) -> Void in
            var index = 0
            for (category, information) in dict as! Dictionary<String, Dictionary<String, AnyObject>> {
                if(Int(information["level"] as! String) == (self.parentCategory.count + 1)) {
                    self.categoryList[index] = Dictionary<String, AnyObject>()
                    var categoryDict = self.categoryList[index]! as! Dictionary<String,AnyObject>

                    categoryDict["name"] = category
                    categoryDict["isLeaf"] = information["isLeaf"] as! Bool
                    categoryDict["id"] = information["cat_id"] as! String
                    categoryDict["level"] = information["level"] as! String
                    
                    self.categoryList[index] = categoryDict
                    
                    index+=1
                }
            }
            self.table.reloadData()
        })
    }
    
    @IBAction func navigateBack() {
        self.categoryList = Dictionary<Int, Dictionary<String,AnyObject>>()
        if(self.parentCategory.count == 1) {
            self.parentCategory.popLast()
            self.presentingViewController?.dismissViewControllerAnimated(true, completion: nil)
        }
        else {
            self.parentCategory.popLast()
            self.loadCategories(self.parentCategory.popLast()! as String, selectedCatCompletion: nil)
        }
    }
}

extension CategoryPopUpController : UITableViewDelegate {
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = self.table.cellForRowAtIndexPath(indexPath)
        var categoryDict = categoryList[indexPath.row] as! Dictionary<String,AnyObject>
        
        if (!(categoryDict["isLeaf"] as! Bool)) {
            self.loadCategories((cell?.textLabel?.text!)!, selectedCatCompletion: nil)
        }else {
            self.completion(categoryDict["id"] as! String, nil)
        }
    }
}

extension CategoryPopUpController: UITableViewDataSource {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.categoryList.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = self.table.dequeueReusableCellWithIdentifier("SubCat Cell")
        var categoryDict = categoryList[indexPath.row] as! Dictionary<String,AnyObject>
        
        cell?.textLabel?.text = categoryDict["name"] as? String
        if (categoryDict["isLeaf"] as! Bool) {
            dispatch_async(dispatch_get_main_queue(), {
                cell?.accessoryView?.hidden = true
            })
        }
        
        return cell!
    }

}
