//
//  CreateGroupViewController.swift
//  PaiAi
//
//  Created by zhengjianfei on 16/4/2.
//  Copyright © 2016年 FFIB. All rights reserved.
//

import UIKit
import PaiaiDataKit
import PaiaiUIKit

protocol CreateGroupViewControllerDelegate: class {
    func didSelect(_ item: GroupItem)
    func navigateToCreateGroupConfirm()
}

final class CreateGroupViewController: AlertViewController {

    // MARK: Storyboard property
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var contentHeightConstraint: NSLayoutConstraint!
    
    weak var delegate: CreateGroupViewControllerDelegate?
    
    override var animationView: UIView? {
        return contentView
    }
    
    override var style: AlertViewController.Style {
        return .actionSheet
    }
    
    // MARK: view function
    override func viewDidLoad() {
        super.viewDidLoad()
        contentHeightConstraint.constant = 48 + 44 * CGFloat(ShareRecentGroupInfo.count + 1)
    }

    // MARK: Storyboard  button function
    @IBAction func cancel() {
        dismissController()
    }
}

extension CreateGroupViewController: UITableViewDataSource, UITableViewDelegate {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ShareRecentGroupInfo.count + 1
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        dismissController()
        switch indexPath.row {
        case 0:
            self.delegate?.navigateToCreateGroupConfirm()
        default:
            self.delegate?.didSelect(ShareRecentGroupInfo[indexPath.row - 1])
        }
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.row {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: "CreateCell", for: indexPath)
            return cell
        default:
            let cell = tableView.dequeueReusableCell(withIdentifier: "RecentCell", for: indexPath)
            let group = ShareRecentGroupInfo[indexPath.row - 1]
            cell.textLabel?.text = group.group_name
            cell.imageView?.setImage(group.group_avatar, placeholder: UIImage(named: "Group\(group.group_default_avatar)"))

            return cell
        }
    }
}