//
//  ActiveSessionsViewController.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 22.05.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

class ActiveSessionsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    let cellIdentifier = "cell"
    var device: Device?
    @IBOutlet weak var dividerViewHeight: NSLayoutConstraint!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var leftButton: UIButton!
    @IBOutlet weak var rightButton: UIButton!
    @IBOutlet weak var dateLabel: UILabel!
    @IBOutlet weak var noDataLabel: UILabel!
    
    var activeSessions: [[AnyObject]] = [] {
        didSet {
            if activeSessions.isEmpty {
                dividerViewHeight.constant = 0
                noDataLabel.hidden = false
            } else {
                dividerViewHeight.constant = 1
                tableView.hidden = false
                noDataLabel.hidden = true
            }
        }
    }
    var currentSessionIndex: Int? {
        didSet {
            if let currentPaymentIndex = currentSessionIndex {
                self.noDataLabel.hidden = true
                let firstSession = (activeSessions[currentPaymentIndex][1] as! [ActiveSession]).first!
                dateLabel.text = firstSession.dateAndMonthFormat()
                changeButton(currentCursorPosition())
                tableView.reloadData()
            } else {
                self.noDataLabel.hidden = false
            }
        }
    }
    
    @IBAction func leftButton_touchUpInside(sender: UIButton) {
        changePeriod(false)
    }
    
    @IBAction func rightButton_touchUpInside(sender: UIButton) {
        changePeriod(true)
    }
    
    private func currentCursorPosition() -> ItemPosition {
        return activeSessions.count == 0 || activeSessions.count == 1 ? .FirstLast : currentSessionIndex == activeSessions.count - 1 ? .Last : currentSessionIndex == 0 ? .First : .None
    }
    
    private func changeButton(itemPosition: ItemPosition) {
        rightButton.hidden = itemPosition == .FirstLast ? true : itemPosition == .Last
        leftButton.hidden = itemPosition == .FirstLast ? true : itemPosition == .First
    }
    
    private func changePeriod(isNext: Bool) {
        if let currentPaymentIndex = currentSessionIndex {
            if isNext {
                self.currentSessionIndex = currentPaymentIndex < activeSessions.count - 1 ? currentPaymentIndex + 1 : currentPaymentIndex
            } else {
                self.currentSessionIndex = currentPaymentIndex > 0 ? currentPaymentIndex - 1 : currentPaymentIndex
            }
        }
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        configureBlueNavbar()
        addBackButtonForDefault(.whiteColor())
        localizeViews()
    }
    
    func localizeViews() {
        localize()
        self.noDataLabel.setTextAndSizeToFit(LS("no_data"))
    }
    
    func loading(enabled: Bool) {
        PKNotification.loading(enabled)
        if enabled {
            noDataLabel.hidden = true
            tableView.hidden = true
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        changeButton(currentCursorPosition())
        configureViews()
        let params = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!,
            "device": self.device!.device!
            ] as [String: AnyObject]
        self.loading(true)
        Facade.sharedInstance().getActiveSessions(params, onSuccess: { (activeSessions) in
            self.activeSessions = activeSessions
            self.activeSessions = activeSessions.sort({ (firstObject, secondObject) -> Bool in
                let dateFirst = (firstObject as! [AnyObject])[0] as! NSDate
                let dateSecond = (secondObject as! [AnyObject])[0] as! NSDate
                return dateFirst.compare(dateSecond) == NSComparisonResult.OrderedAscending
            })
            self.currentSessionIndex = activeSessions.count > 0 ? activeSessions.count - 1 : nil
            }, onError: { (error) in
                self.noDataLabel.hidden = false
                AlertViewUtil.showIncorrectAlert(error)
            }, onFinish: {() in
                self.loading(false)
        })
    }
    
    func configureViews() {
        dateLabel.textColor = Color.DarkColorForText
        noDataLabel.textColor = Color.DarkColorForText
        self.view.bringSubviewToFront(noDataLabel)
        configureTableView()
    }
    
    private func configureTableView() {
        tableView.estimatedRowHeight = 280
        tableView.rowHeight = UITableViewAutomaticDimension
    }
    
}

extension ActiveSessionsViewController {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        cell?.selected = false
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return activeSessions.count > 0 ? (activeSessions[currentSessionIndex!][1] as! [ActiveSession]).count : 0
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ActiveSessionsCell
        cell.fillCell((activeSessions[currentSessionIndex!][1] as! [ActiveSession])[indexPath.row])
        cell.selectionStyle = .None
        return cell
    }
}

extension ActiveSessionsViewController {
    override var localizedId: String {
        return "active_sessions"
    }
}
