//
//  ServiceVIPTableViewController.swift
//  kt
//
//  Created by neox on 06.11.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import Foundation

class ServiceVIPTableViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var serviceItem : ServiceItem?
    
    @IBOutlet weak var tableView: UITableView!
    
    var totalPrice = 0
    var selection = [true, false, false, false, false, false, false, false, false, false, false, false, false]
    var prices =  [6999, 1000, 1500, 2000, 9000, 1000, 1999, 1000, 1500, 1000, 799, 600, 0]
    var amounts = [1,1,1,1,1,1,1,1,1,1,1,1,1]
    
    var lastCellCreated = false
    
    var rowsHeight = [NSIndexPath: CGFloat]()
    var additionalTitles = [
        LS("service_vip"),
        LS("service_vip_tv"),
        LS("service_vip_mobile"),
        LS("service_vip_gamer"),
        LS("service_vip_max"),
        LS("service_vip_additional_1"),
        LS("service_vip_additional_2"),
        LS("service_vip_additional_3"),
        LS("service_vip_additional_4"),
        LS("service_vip_additional_5"),
        LS("service_vip_additional_6"),
        LS("service_vip_additional_7"),
        ""
    ]
    var serviceTotal = ""
    
    var optionRussianPhone = false
    //var optionTVPackageNastroiKino = false
    var optionTVPackageIndex = 0
    
    @IBAction func connectButton(sender: UIButtonRoundedBlue) {
        let vc = self.storyboard!.instantiateViewControllerWithIdentifier("CallbackViewController") as! CallbackViewController
        vc.service_id = serviceItem?.id
        vc.type = 2 // HOT - заказ услуги
        vc.user_comment = serviceTotal
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func callBackButton(sender: UIButtonRoundedGray) {
        let vc = self.storyboard!.instantiateViewControllerWithIdentifier("CallbackViewController") as! CallbackViewController
        vc.service_id = serviceItem?.id
        vc.type = 1 // COLD - обратный звонок
        vc.user_comment = serviceTotal
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    override func loadView() {
        super.loadView()
        
        self.title = serviceItem?.name
        requestService()
        tableView.allowsMultipleSelection = true
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tableView.dataSource = self
        self.tableView.delegate = self
        
        //        tableView.rowHeight = UITableViewAutomaticDimension
        //        tableView.estimatedRowHeight = 60
        
        selectRow(0)
    }
    
    func selectRow(row: Int) {
        let indexPath = NSIndexPath(forRow: row, inSection: 0);
        self.tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: UITableViewScrollPosition.None)
        self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)
        //        let cell = tableView.cellForRowAtIndexPath(indexPath)
        //        cell!.setSelected(true, animated: false)
    }
    
    func deselectRow(row: Int) {
        let indexPath = NSIndexPath(forRow: row, inSection: 0);
        self.tableView.deselectRowAtIndexPath(indexPath, animated: false)
        self.tableView(self.tableView, didDeselectRowAtIndexPath: indexPath)
        //        let cell = tableView.cellForRowAtIndexPath(indexPath)
        //        cell!.setSelected(false, animated: false)
    }
    
    func load() {
        
    }
    
    func requestService() {
        let params: [String: AnyObject] = ["service_id": (serviceItem?.id)!, "type": "landing" ]
        
        Facade.sharedInstance().getLanding(params, onSuccess: { (serviceItem) in
            self.serviceItem = serviceItem
            self.load()
            }, onError: { (error) in
                print(error)
            }, onFinish: {
        })
    }
    
}

extension ServiceVIPTableViewController {
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var cell = UITableViewCell()
        switch indexPath.row {
        case 0:
            let myCell = tableView.dequeueReusableCellWithIdentifier("VIPCell", forIndexPath: indexPath) as! VIPCell
            myCell.vc = self
            myCell.price = prices[0]
            cell = myCell
            break
            
        case 1:
            let myCell = tableView.dequeueReusableCellWithIdentifier("VIPTVCell", forIndexPath: indexPath) as! VIPTVCell
            myCell.vc = self
            myCell.price = prices[1]
            cell = myCell
            break
            
        case 2:
            let myCell = tableView.dequeueReusableCellWithIdentifier("VIPMobileCell", forIndexPath: indexPath) as! VIPMobileCell
            myCell.vc = self
            myCell.price = prices[2]
            cell = myCell
            break
            
        case 3:
            //            cell = UITableViewCell()
            //            cell.textLabel?.text = "VIP Gamer"
            let myCell = tableView.dequeueReusableCellWithIdentifier("VIPGamer", forIndexPath: indexPath) as! VIPGamer
            myCell.vc = self
            cell = myCell
            break
            
        case 4:
            let myCell = tableView.dequeueReusableCellWithIdentifier("VIPMax", forIndexPath: indexPath) as! VIPMax
            myCell.vc = self
            cell = myCell
            break
            
        case 5,6,7,8,9:
            let myCell = tableView.dequeueReusableCellWithIdentifier("VIPAdditional", forIndexPath: indexPath) as! VIPAdditional
            myCell.vc = self
            myCell.label.text = additionalTitles[indexPath.row]
            myCell.indexPath = indexPath
            myCell.setPrice(prices[indexPath.row])
            cell = myCell
            myCell.setOn(selection[indexPath.row])
            break
            
        case 10, 11:
            let myCell = tableView.dequeueReusableCellWithIdentifier("VIPAdditionalStepper", forIndexPath: indexPath) as! VIPAdditionalStepper
            myCell.vc = self
            myCell.label.text = additionalTitles[indexPath.row]
            myCell.indexPath = indexPath
            myCell.setPrice(prices[indexPath.row])
            myCell.setAmount(amounts[indexPath.row])
            cell = myCell
            myCell.setOn(selection[indexPath.row])
            break
            
        case 12:
            let myCell = tableView.dequeueReusableCellWithIdentifier("VIPTotal", forIndexPath: indexPath) as! VIPTotal
            myCell.vc = self
            myCell.updateTotal()
            cell = myCell
            lastCellCreated = true
            break
            
        default:
            break
        }
        
        //setSelection(indexPath.row, selected: selection[indexPath.row])
        
        return cell
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 13
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print(indexPath.row)
        setSelection(indexPath.row, selected: true)
        if ( 1 <= indexPath.row && indexPath.row <= 4 ) {
            for index in 1...4 {
                if ( index == indexPath.row ) {
                    
                } else {
                    deselectRow(index)
                }
            }
        }
        else if ( 5 <= indexPath.row && indexPath.row <= 9 ) {
            let cell = tableView.cellForRowAtIndexPath(indexPath) as! VIPAdditional
            cell.setOn(true)
        }
        else if ( 10 <= indexPath.row && indexPath.row <= 11 ) {
            let cell = tableView.cellForRowAtIndexPath(indexPath) as! VIPAdditionalStepper
            cell.setOn(true)
        }
        updateTotal()
    }
    
    func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
        print(indexPath.row)
        setSelection(indexPath.row, selected: false)
        if ( indexPath.row == 0 ) {
            selectRow(0)
        }
        else if ( 5 <= indexPath.row && indexPath.row <= 9) {
            let cell = tableView.cellForRowAtIndexPath(indexPath) as! VIPAdditional
            cell.setOn(false)
        }
        else if ( 10 <= indexPath.row && indexPath.row <= 11) {
            let cell = tableView.cellForRowAtIndexPath(indexPath) as! VIPAdditionalStepper
            cell.setOn(false)
        }
        updateTotal()
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        rowsHeight[indexPath] = cell.frame.height
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if ( indexPath.row == numberOfRows() - 1 ) {
            return UITableViewAutomaticDimension
        }
        if let rowHeight = rowsHeight[indexPath] {
            return rowHeight
        }
        return UITableViewAutomaticDimension
    }
    
    func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 120.0
    }
    
    
    func isSelected(row: Int) -> Bool {
        let indexPath =  NSIndexPath(forRow: row, inSection: 0)
        return tableView.cellForRowAtIndexPath(indexPath)!.selected
    }
    
    func setSelection(index:Int, selected: Bool ) {
        selection[index] = selected
        print("selecting: \(index), value: " + String(selected))
    }
    
    func updateTotal() {
        totalPrice = 0
        serviceTotal = ""
        for index in 0...numberOfRows()-1 {
            if ( index == 5 && selection[index] && optionTVPackageIndex == 2 && selection[1] ) {
                // skip
                print("nastroi kino - true")
            }
            else if ( index == 7 && selection[index] && optionRussianPhone ) {
                // skip
                print("russian phone - true")
            }
            else if ( index == 8 && selection[index] && selection[1] && optionTVPackageIndex == 1 ) {
                // skip
                print("hd base")
            }
            else if ( index == 9 && selection[index] && selection[1] && optionTVPackageIndex == 0 ) {
                // skip
                print("id tv online")
            }
            else if ( selection[4] && 5 <= index && index <= 9 && (selection[5] || selection[6] || selection[7] || selection[8] || selection[9] )) {
                // if vip max is selected, then skip additionals
                print("vip max - true")
            }
            else if ( selection[index] ) {
                totalPrice += prices[index] * amounts[index]
            }
            
            if ( selection[index] ) {
                if ( index != 0 )  {
                    serviceTotal = serviceTotal + ", "
                }
                if ( amounts[index] > 1 ) {
                    serviceTotal = serviceTotal + " " + String(amounts[index]) + " "
                }
                serviceTotal = serviceTotal + additionalTitles[index]
            }
        }
        print(serviceTotal)
        print("total price: \(totalPrice)")
        
        reloadLastCell()
    }
    
    func reloadLastCell() {
        if ( self.lastCellCreated ) {
            let indexPath = NSIndexPath(forRow: numberOfRows()-1, inSection: 0)
            self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.None)
        }
    }
    
    func numberOfRows() -> Int {
        return tableView.numberOfRowsInSection(0)
    }
    
    func getTotalPrice() -> Int {
        return totalPrice
    }
    
//    func additionalSwitch(indexPath: NSIndexPath, isOn: Bool) {
//        selection[indexPath.row] = isOn
//        updatePrices()
//    }

    func setRowSelected(indexPath: NSIndexPath, isOn : Bool ) {
        if ( isOn ) {
            self.tableView.selectRowAtIndexPath(indexPath, animated: true, scrollPosition: UITableViewScrollPosition.None)
            self.tableView(self.tableView, didSelectRowAtIndexPath: indexPath)
        } else {
            self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
            self.tableView(self.tableView, didDeselectRowAtIndexPath: indexPath)
        }
    }
    
    func getVIPGamerPrice() -> Int {
        return prices[5]
    }
    
    func getAmount(index: Int ) -> Int {
        return amounts[index]
    }
    
    func incrementAmount(index: Int) {
        amounts[index] = amounts[index] + 1
    }
    
    func setBoolOptionRussianPhone(bool: Bool) {
        optionRussianPhone = bool
        updateTotal()
    }
    
    func setOptionTVPackage(index: Int) {
        optionTVPackageIndex = index
        updateTotal()
    }
    
//    func setBoolOptionTVPackageNastroiKino(bool: Bool) {
//        optionTVPackageNastroiKino = bool
//        updateTotal()
//    }
    
    func decrementAmount(index: Int) {
        amounts[index] = amounts[index] - 1
    }
    
    func setAmount(index: Int, amount: Int ) {
        amounts[index] = amount
        
        updateTotal()
    }
    
    func getServicesTotal() -> String {
        return serviceTotal
    }
    
}

class VIPOptionCell : UITableViewCell {
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        self.selectionStyle = UITableViewCellSelectionStyle.None
        self.textLabel?.font = UIFont(name: (self.textLabel?.font?.fontName)!, size:13)
    }
    
}
