//
//  UIListBoxViewController.swift
//  kt
//
//  Created by Admin on 17.12.16.
//  Copyright © 2016 SimpleCode. All rights reserved.
//

import Foundation

@objc protocol ListBoxItemProtocol {   
    var listItemTitle : String {get}
}


@objc protocol UIListBoxViewControllerDelegate{
    
    func didSelectItem(listBoxViewController: UIListBoxViewController, selectedListBoxItem: ListBoxItemProtocol, numberIndex: NSNumber)
    
}

class UIListBoxViewController : UIViewController, UITableViewDelegate, UITableViewDataSource {
   
    @IBOutlet weak var tableView: UITableView!
    internal var listBoxItems : [ListBoxItemProtocol]?
    internal var delegate : UIListBoxViewControllerDelegate?
    
    internal var cellsData : [ListBoxItemCellData] = []
    internal var tag : Int = 0    
    
    //MARK: System

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        configureBlueNavbar()
        addBackButtonForDefault(.whiteColor())
        
        self.tableView.rowHeight = UITableViewAutomaticDimension;
        self.tableView.estimatedRowHeight = 44.0;
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        createCells()
        tableView.reloadData()
        self.configureBlueNavbar()
    }
    
    //MARK: Private Functions
    
    private func createCells() {
        cellsData = []
        var index : Int = 0
        for listBoxItem in listBoxItems! {
            let cellData = ListBoxItemCellData(listBoxItem: listBoxItem)
            cellsData.append(cellData)
            index = index + 1
        }
    }   
    
}

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

//MARK: UITableViewDelegate
extension UIListBoxViewController {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cellData = cellsData[indexPath.row]
        if (self.delegate != nil) {
            self.delegate?.didSelectItem(self, selectedListBoxItem: cellData.listBoxItem!, numberIndex: NSNumber(integer: indexPath.row))
        }
        self.back()
    }

}
