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

import Foundation
import UIKit

class ClaimListViewController: UIViewController, StoryboardFetchable, UITableViewDataSource, UITableViewDelegate, UIListBoxViewControllerDelegate {
    
    //MARK: - IBOutles
    
    @IBOutlet weak var topWrapperView: UIView!
    @IBOutlet weak var dividerView: UIView!
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var reload: UIButtonRoundedBlue!
    
    //MARK: - Vars
    
    static var storyboardId = "ClaimList"
    
    var dateStart: NSDate? {
        didSet {
            if let dateStart = dateStart {
                createCellDataSelectDate(dateStart)
            }
        }
    }
    
    var currentSiebelAccountData: SiebelAccount.SiebelAccountData? {
        didSet {
            createCellDataSelectDeviceId(currentSiebelAccountData!)
            if viewDidLoaded {
                requestSiebelData()
            }
        }
    }
    
    var claims: [Claim] = [] {
        didSet {
            updateServiceStatementCells(claims)
        }
    }
    
    var fullDamages: [FullDamage] = [] {
        didSet {
            updateRepairBureaCells(fullDamages)
        }
    }
    
    
    
    
    var cellDataSelectDate : TitleValueCellData?
    var cellDataSelectDeviceId : TitleValueCellData?
    
    var cellsRepairBureauItem : [CellData] = []
    var cellsServiceStatementItem : [CellData] = []
    
    var viewDidLoaded = false
    var siebelAccount: SiebelAccount!
    var siebelAccountDataListNames: [String] = []
    
    var vc: ClaimPageMenuViewController!
    var tabIndex: Int = 0
    
    //MARK: - Functions
    
    func deleteClaim(claim : Claim, sender: UIViewController) {
        let alert = UIAlertController(title: "\(LS("claim_page.menu.delete_claim_sc")) \(claim.claimId ?? "")?", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: LS("cancel"), style: .Cancel, handler: nil))
        alert.addAction(UIAlertAction(title: LS("ok"), style: UIAlertActionStyle.Default, handler: { (alertAction) in
            sender.back()
            let params: [String: AnyObject] = ["server_id": Facade.serverId!,
                                               "abonent_id": Facade.accountId!,
                                               "client_id": Facade.clientId!,
                                               "access_token": Facade.accessToken!,
                                               "claim_number": claim.claimNumber ?? ""]
            PKNotification.loading(true)
            //self.view.userInteractionEnabled = false
            self.vc.view.userInteractionEnabled = false
            Facade.sharedInstance().claimDelete(params, onSuccess: {
                //self.tableView.reloadData()
                AlertViewUtil.showMessageAlert(LS("claim_page.menu.deleted_claim_successfully"), vc: self)
                PKNotification.loading(false)
                self.vc.view.userInteractionEnabled = true
                self.requestSiebelData()
                }, onError: { (error) in
                    AlertViewUtil.showErrorAlert(error, vc: self)
                    PKNotification.loading(false)
                    self.vc.view.userInteractionEnabled = true
                }, onFinish: {
            })
        }))
        sender.presentViewController(alert, animated: true, completion: nil)
    }
    
    func deleteFullDamage(fullDamage : FullDamage, sender: UIViewController) {
        let alert = UIAlertController(title: "\(LS("claim_page.menu.delete_claim")) \(fullDamage.damageId ?? "")?", message: nil, preferredStyle: UIAlertControllerStyle.Alert)
        alert.addAction(UIAlertAction(title: LS("cancel"), style: .Cancel, handler: nil))
        alert.addAction(UIAlertAction(title: LS("ok"), style: UIAlertActionStyle.Default, handler: { (alertAction) in
            sender.back()
            let params: [String: AnyObject] = ["server_id": Facade.serverId!,
                                               "abonent_id": Facade.accountId!,
                                               "client_id": Facade.clientId!,
                                               "access_token": Facade.accessToken!,
                                               "damage_number": fullDamage.damageNumber ?? ""]
            PKNotification.loading(true)
            self.vc.view.userInteractionEnabled = false
            Facade.sharedInstance().damageDelete(params, onSuccess: {
                //self.tableView.reloadData()
                AlertViewUtil.showMessageAlert(LS("claim_page.menu.deleted_claim_successfully"), vc: self)
                PKNotification.loading(false)
                self.vc.view.userInteractionEnabled = true
                self.requestSiebelData()
                }, onError: { (error) in
                    AlertViewUtil.showErrorAlert(error, vc: self)
                    PKNotification.loading(false)
                    self.vc.view.userInteractionEnabled = true
                }, onFinish: {
                    
            })
        }))
        sender.presentViewController(alert, animated: true, completion: nil)
    }
    
    func updateRepairBureaCells(fullDamages : [FullDamage]) {
        cellsRepairBureauItem = []
        cellsRepairBureauItem.append(cellDataSelectDate!)
        cellsRepairBureauItem.append(cellDataSelectDeviceId!)
        for item in fullDamages {
            let cellData = RBCellData(fullDamage: item, onClick: {
                self.vc.selectedFullDamage = item
                self.vc.performSegueWithIdentifier(Segue.FullDamageModal, sender: self.tabIndex)
            })
            cellData.valueText = removePrefix(cellData.valueText)
            cellsRepairBureauItem.append(cellData)
        }
        tableView?.reloadData()
    }
    
    func updateServiceStatementCells(claims: [Claim]) {
        cellsServiceStatementItem = []
        cellsServiceStatementItem.append(cellDataSelectDate!)
        cellsServiceStatementItem.append(cellDataSelectDeviceId!)
        for item in claims {
            let cellData = RBCellData(claim: item, onClick: {
                self.vc.selectedClaim = item
                self.vc.performSegueWithIdentifier(Segue.FullDamageModal, sender: self.tabIndex)
            })
            cellData.valueText = removePrefix(cellData.valueText)
            cellsServiceStatementItem.append(cellData)
        }
        tableView?.reloadData()
    }
    
    func createCellDataSelectDate(date : NSDate) {
        cellDataSelectDate = TitleValueCellData.init(title: LS("claim_page_menu.cell.date_title").uppercaseString, value: date.getWithFormat("yyyy-MM-dd"), onClick: {
            self.showDateSelection()
        })
        
    }
    
    func createCellDataSelectDeviceId(siebelAccountData : SiebelAccount.SiebelAccountData) {
        cellDataSelectDeviceId = TitleValueCellData.init(title: LS("claim_page_menu.cell.deviceId_title").uppercaseString, value: ("\(siebelAccountData.assetNumber ?? "") \(siebelAccountData.deviceGroupName ?? "")").uppercaseString, onClick: {
            self.showSelectDevices()
        })
    }
    
    func removePrefix(text : String) -> String {
        var result = text
        let range : Range<String.Index>? = text.rangeOfString(" ")
        if (range != nil) {
            //let index : Int = text.startIndex.distanceTo(range.startIndex)
            let rangeSecondWord = range!.endIndex..<text.endIndex
            result = text[rangeSecondWord]
        }
        return result
    }
    
    func requestSiebelData() {
        //    index
        if let currentSiebelAccountData = currentSiebelAccountData {
            if tabIndex == 0 {
                let params: [String: AnyObject] = ["server_id": Facade.serverId!,
                                                   "abonent_id": Facade.accountId!,
                                                   "client_id": Facade.clientId!,
                                                   "dateStart": dateStart!.getWithFormat("dd.MM.yyyy"),
                                                   "assetNumber": currentSiebelAccountData.assetNumber!,
                                                   "access_token": Facade.accessToken!]
                self.vc.processRequest(true)
                Facade.sharedInstance().getDamageList(params, onSuccess: { (fullDamages) in
                    self.fullDamages = fullDamages
                    self.vc.processRequest(false)
                    self.reload.hidden = true
                    }, onError: { (error) in
                        self.fullDamages = []
                        AlertViewUtil.showErrorAlert(error, vc: self)
                        self.vc.processRequest(false)
                        self.reload.hidden = false
                    }, onFinish: {
                        
                })
            } else {
                let params: [String: AnyObject] = ["server_id": Facade.serverId!,
                                                   "abonent_id": Facade.accountId!,
                                                   "client_id": Facade.clientId!,
                                                   "dateStart": dateStart!.getWithFormat("dd.MM.yyyy"),
                                                   "assetNumber": currentSiebelAccountData.assetNumber!,
                                                   "access_token": Facade.accessToken!,
                                                   "type": "claim"]
                self.vc.processRequest(true)
                Facade.sharedInstance().getClaimList(params, onSuccess: { (claims) in
                    self.claims = claims
                    self.vc.processRequest(false)
                    self.reload.hidden = true
                    }, onError: { (error) in
                        self.claims = []
                        AlertViewUtil.showErrorAlert(error, vc: self)
                        self.vc.processRequest(false)
                        self.reload.hidden = false
                    }, onFinish: {
                        
                })
            }
        }
    }
    
    func fillDataList() {
        for item in self.siebelAccount.siebelAccountDataList {
            siebelAccountDataListNames.append(("\(item.assetNumber ?? "") \(item.deviceGroupName ?? "")").uppercaseString)
        }
    }
    
    func configureViews() {
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 150
        dividerView.backgroundColor = Color.GrayTableCellSeparator
    }
    
    func showDateSelection() {
        let datePicker = ActionSheetDatePicker(title: LS("claim_page_menu.cell.date_title"), datePickerMode: UIDatePickerMode.Date, selectedDate: self.dateStart!, doneBlock: {
            picker, value, index in
            if (self.dateStart?.compare((value as? NSDate)!) != NSComparisonResult.OrderedSame) {
                self.dateStart = value as? NSDate
                self.requestSiebelData()
            }
            return
            }, cancelBlock: { ActionStringCancelBlock in return }, origin: self.view)
        let secondsInWeek: NSTimeInterval = 100 * 365 * 24 * 60 * 60;
        datePicker.minimumDate = NSDate(timeInterval: -secondsInWeek, sinceDate: NSDate())
        datePicker.maximumDate = NSDate().myDateByAddingDays(-31)
        datePicker.setDoneButton(UIBarButtonItem(title: LS("ok"), style: .Plain, target: self, action: Selector()))
        datePicker.setCancelButton(UIBarButtonItem(title: LS("cancel"), style: .Plain, target: nil, action: Selector()))
        datePicker.showActionSheetPicker()
    }
    
    func showDeviceIdSelection() {
        if let currentSiebelAccountData = self.currentSiebelAccountData where !self.siebelAccountDataListNames.isEmpty {
            let acp = ActionSheetMultipleStringPicker(title: "", rows: [self.siebelAccountDataListNames], initialSelection: [self.siebelAccountDataListNames.indexOf(("\(currentSiebelAccountData.assetNumber ?? "") \(currentSiebelAccountData.deviceGroupName ?? "")").uppercaseString)!], doneBlock: {
                picker, values, indexes in
                self.vc.selectedSiebelAccountDataIndex = (values[0] as! NSNumber).integerValue
                if (self.currentSiebelAccountData?.assetId?.compare(self.siebelAccount.siebelAccountDataList[values[0] as! Int].assetId!) != NSComparisonResult.OrderedSame) {
                    dispatch_async(dispatch_get_main_queue()){
                        //
                        self.currentSiebelAccountData = self.siebelAccount.siebelAccountDataList[values[0] as! Int]
                    }
                    return
                }
                }, cancelBlock: { ActionMultipleStringCancelBlock in return }, origin: self.view)
            
            acp.setDoneButton(UIBarButtonItem(title: LS("ok"), style: .Plain, target: self, action: Selector()))
            acp.setCancelButton(UIBarButtonItem(title: LS("cancel"), style: .Plain, target: nil, action: Selector()))
            acp.showActionSheetPicker()
        }
        
    }
    
    func showSelectDevices() {
        let vc = storyboard?.instantiateViewControllerWithIdentifier("listBoxViewControllerIdentifier") as! UIListBoxViewController
        vc.listBoxItems = self.siebelAccount.siebelAccountDataList
        vc.title = LS("claim_page_menu.cell.deviceId_title")
        vc.delegate = self
        self.vc.showViewController(vc, sender: self)
        //showViewController(vc, sender: self)
    }
    
    //MARK: - IBActions
    
    @IBAction func reloadAction(sender: AnyObject) {
        requestSiebelData()
    }
    
    //MARK: - System
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.showsVerticalScrollIndicator = false
        reload.hidden = true
        reload.titleLabel?.text = LS("reloadRequest")
        let currentDate = NSDate()
        self.dateStart = currentDate.myDateByAddingDays(-31)
        
        configureViews()
        requestSiebelData()
        
        viewDidLoaded = true
    }
    
}

//MARK: UIListBoxViewControllerDelegate
extension ClaimListViewController {
    
    func didSelectItem(listBoxViewController: UIListBoxViewController, selectedListBoxItem: ListBoxItemProtocol, numberIndex: NSNumber) {
        let index = numberIndex.integerValue
        self.vc!.selectedSiebelAccountDataIndex = index
        if (self.currentSiebelAccountData?.assetId?.compare(self.siebelAccount.siebelAccountDataList[index].assetId!) != NSComparisonResult.OrderedSame) {
            dispatch_async(dispatch_get_main_queue()){
                self.currentSiebelAccountData = self.siebelAccount.siebelAccountDataList[index]
            }
        }
    }
    
}

// UITableViewDelegate
extension ClaimListViewController {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let cell = tableView.cellForRowAtIndexPath(indexPath) as! UIBaseTableViewCell
        cell.selectionStyle = .None
        cell.cellData?.onClick()
    }
}

// UITableViewDataSource
extension ClaimListViewController {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return tabIndex == 0 ? cellsRepairBureauItem.count : cellsServiceStatementItem.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellsData = tabIndex == 0 ? cellsRepairBureauItem : cellsServiceStatementItem
        let cellData = cellsData[indexPath.row]
        let cell = CellsManager.CreateCell(tableView, cellType: cellData.cellType)
        cell.fillWithCellData(cellData)
        return cell
    }
}
