//
//  ViewController.swift
//  UseForwardDelegates
//
//  Created by Scott Gardner on 6/5/16.
//  Copyright © 2016 Scott Gardner. All rights reserved.
//

import UIKit
import RxSwift
import RxDataSources

class ViewController: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    let model = Model()
    let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Contributor>>()
    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        dataSource.configureCell = { _, tableView, indexPath, contributor in
            let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
            cell.imageView?.image = contributor.image
            cell.textLabel?.text = contributor.name
            cell.detailTextLabel?.text = contributor.gitHubID
            return cell
        }
        
        model.data
            .bindTo(tableView.rx_itemsWithDataSource(dataSource))
            .addDisposableTo(disposeBag)
        
        dataSource.titleForHeaderInSection = {
            $0.sectionAtIndex($1).model
        }
        
        tableView.rx_setDelegate(self)
            .addDisposableTo(disposeBag)
        
        dataSource.titleForHeaderInSection = { data, section in
            data.sectionAtIndex(section).model
        }
    }

}

extension ViewController: UITableViewDelegate {
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return CGFloat(arc4random_uniform(96) + 32)
    }
}
