//
//  AccountServicesViewController.swift
//  kt
//
//  Created by neox on 01.07.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import UIKit

class AccountServicesViewController: ViewControllerWithMenu {
    
    @IBOutlet weak var tableView: UITableView!
    
    var accountServices: AccountServices?
    
    override func viewDidLoad() {
        
        super.viewDidLoad()
        
        self.navigationItem.title = "Мои услуги"
        
        configureRightIDTVCreate()
        
        getDevices()
    
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        configureBlueNavbar()
    }
    
    func getDevices() {
        self.processRequest(true)
        Facade.sharedInstance().getAccountServices({ accountServices in
            self.accountServices = accountServices
            self.tableView.reloadData()
            }, onError: { error in
                AlertViewUtil.showErrorAlert(error, vc: self)
        }) {
            self.processRequest(false)
        }
    }
    
    func configureRightIDTVCreate() {
//        let barButtonItem = UIBarButtonItem(title: LS("my_services_navigationRightButton_createIDTV"), style: .Plain, target: self, action: #selector(self.showCreateIDTV(_:)))
//        barButtonItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFontOfSize(11), NSForegroundColorAttributeName: UIColor.whiteColor()], forState: .Normal)
//        self.navigationItem.rightBarButtonItem = barButtonItem
    }
    
    func showCreateIDTV(sender: UIBarButtonItem) {
        let vc = self.storyboard!.instantiateViewControllerWithIdentifier("UICreateIDTVViewController") as! UICreateIDTVViewController
        self.navigationController?.pushViewController(vc, animated: true)
    }
}

extension AccountServicesViewController {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        defer { tableView.deselectRowAtIndexPath(indexPath, animated: true)}
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCellWithIdentifier("AbonentServicesCell", forIndexPath: indexPath) as! AbonentServicesCell
        
        guard accountServices != nil else {
            return cell
        }
        
        switch indexPath.section {
        case Sections.Phones:
            
            cell.title.text = "Телефон"
            cell.number.text = accountServices!.telephones[indexPath.row]
            cell.accessoryView?.hidden = true
            
            return cell
            
        case Sections.Altel:
            
            cell.title.text = "Altel 4g"
            cell.number.text = accountServices!.altel4G[indexPath.row]
            
            let infoButton = UIButton(type: .Custom)
            infoButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
            infoButton.tag = indexPath.row
            infoButton.addTarget(self, action: #selector(self.altel4gAction(_:event:)), forControlEvents: .TouchUpInside)
            infoButton.setImage(UIImage(named: "cpanel_actionlist_icon_tap.png"), forState: .Normal)
            
            cell.accessoryView = infoButton as UIView
            
            return cell
            
        case Sections.Megaline:
            
            cell.title.text = accountServices!.megalineIdNets[indexPath.row].name
            cell.number.text = accountServices!.megalineIdNets[indexPath.row].device
            
            let infoButton = UIButton(type: .Custom)
            infoButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
            infoButton.tag = indexPath.row
            infoButton.addTarget(self, action: #selector(self.megalineInfoAction(_:event:)), forControlEvents: .TouchUpInside)
            infoButton.setImage(UIImage(named: "cpanel_actionlist_icon_tap.png"), forState: .Normal)

            cell.accessoryView = infoButton as UIView
            
            return cell
            
        case Sections.idTvOnline:
            
            cell.title.text = accountServices!.idTvOnlines[indexPath.row].name
            cell.number.text = accountServices!.idTvOnlines[indexPath.row].device
            
            let infoButton = UIButton(type: .Custom)
            infoButton.frame = CGRect(x: 0, y: 0, width: 24, height: 24)
            infoButton.tag = indexPath.row
            infoButton.addTarget(self, action: #selector(self.iDTVOnlineAction(_:event:)), forControlEvents: .TouchUpInside)
            infoButton.setImage(UIImage(named: "cpanel_actionlist_icon_tap.png"), forState: .Normal)
        
            cell.accessoryView = infoButton as UIView
            cell.accessoryView?.hidden = true
            
            return cell
            
        case Sections.idPhone:
            
            cell.title.text = accountServices!.idPhone[indexPath.row].name
            cell.number.text = accountServices!.idPhone[indexPath.row].number
            
            return cell
            
        default:
            return cell
        }
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        guard accountServices != nil else {
            return 0
        }
        
        switch section {
        case Sections.Phones: return accountServices!.telephones.count
        case Sections.Altel: return accountServices!.altel4G.count
        case Sections.Megaline: return accountServices!.megalineIdNets.count
        case Sections.idTvOnline: return accountServices!.idTvOnlines.count
        case Sections.idPhone: return accountServices!.idPhone.count
        default: return 0
        }
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return Sections.Count
    }
    
    func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        guard accountServices != nil else { return nil }
        switch section {
        case Sections.Phones where !accountServices!.telephones.isEmpty:
            return "Телефон"
        case Sections.Altel where !accountServices!.altel4G.isEmpty:
            return "Altel 4G"
        case Sections.Megaline where !accountServices!.megalineIdNets.isEmpty:
            return "Megaline iDNet"
        case Sections.idTvOnline where !accountServices!.idTvOnlines.isEmpty:
            return "iDTV online"
        case Sections.idPhone where !accountServices!.idPhone.isEmpty:
            return "iDPhone"
        default:
            return nil
        }
    }
    
    func megalineInfoAction(sender: UIButton, event: AnyObject) {
        
        let index = sender.tag
        
        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
        
        actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
        actionSheet.popoverPresentationController?.sourceView = self.view
        actionSheet.popoverPresentationController?.sourceRect = CGRect(origin: CGPoint(x: CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds)), size: CGSizeZero)
        
        actionSheet.addAction(UIAlertAction(title: "История подключения", style: .Default, handler: { _ in
            
            let device = Device()
            device.device = self.accountServices?.megalineIdNets[index].device
            
            let vc = self.storyboard!.instantiateViewControllerWithIdentifier("SubscribeHistoryViewController") as! SubscribeHistoryViewController
            vc.device = device
            self.navigationController?.pushViewController(vc, animated: true)
            
        }))
        
        actionSheet.addAction(UIAlertAction(title: "Активные сессии", style: .Default, handler: { _ in
            
            let device = Device()
            device.device = self.accountServices?.megalineIdNets[index].device
            
            let vc = self.storyboard!.instantiateViewControllerWithIdentifier("ActiveSessionsViewController") as! ActiveSessionsViewController
            vc.device = device
            self.navigationController?.pushViewController(vc, animated: true)
            
        }))
        
        actionSheet.addAction(UIAlertAction(title: "Настройки", style: .Default, handler: { _ in
            
            let device = Device()
            device.device = self.accountServices?.megalineIdNets[index].device
            
            let vc = self.storyboard!.instantiateViewControllerWithIdentifier("DeviceSettingsViewController") as! DeviceSettingsViewController
            vc.device = device
            self.navigationController?.pushViewController(vc, animated: true)
            
        }))
        
        actionSheet.addAction(UIAlertAction(title: "Общественный Wi-Fi", style: .Default, handler: { _ in
            
            let device = Device()
            device.device = self.accountServices?.megalineIdNets[index].device
            device.linkId = self.accountServices?.megalineIdNets[index].linkID
            
            let vc = self.storyboard!.instantiateViewControllerWithIdentifier("PublicWifiViewController") as! PublicWifiViewController
            vc.device = device
            self.navigationController?.pushViewController(vc, animated: true)
            
        }))
        
        actionSheet.addAction(UIAlertAction(title: "Отмена", style: .Cancel, handler: nil))
        self.presentViewController(actionSheet, animated: true, completion: nil)
    }
    
    func iDTVOnlineAction(sender: UIButton, event: AnyObject) {
        
        let index = sender.tag
        
        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
        
        actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
        actionSheet.popoverPresentationController?.sourceView = self.view
        actionSheet.popoverPresentationController?.sourceRect = CGRect(origin: CGPoint(x: CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds)), size: CGSizeZero)
        
        actionSheet.addAction(UIAlertAction(title: "Удалить", style: .Default, handler: { _ in
            
            let device = Device()
            device.device = self.accountServices?.idTvOnlines[index].device
            device.connectTypeId = String(self.accountServices?.idTvOnlines[index].typeID)
            
            self.sendRequestRemoveIDTV(device)
            
        }))
        
        actionSheet.addAction(UIAlertAction(title: "Отмена", style: .Cancel, handler: nil))
        self.presentViewController(actionSheet, animated: true, completion: nil)
    }
    
    func altel4gAction(sender: UIButton, event: AnyObject) {
        
        let index = sender.tag
        
        let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
        
        actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
        actionSheet.popoverPresentationController?.sourceView = self.view
        actionSheet.popoverPresentationController?.sourceRect = CGRect(origin: CGPoint(x: CGRectGetMidX(self.view.bounds), y: CGRectGetMidY(self.view.bounds)), size: CGSizeZero)
        
        actionSheet.addAction(UIAlertAction(title: "Детализация", style: .Default, handler: { _ in
            
            let device = Device()
            device.device = self.accountServices?.altel4G[index]
            
            let vc = self.storyboard!.instantiateViewControllerWithIdentifier("DetalizationViewController") as! DetalizationViewController
            vc.phone = device.device
            self.navigationController?.pushViewController(vc, animated: true)
            
        }))
        
        actionSheet.addAction(UIAlertAction(title: "Отмена", style: .Cancel, handler: nil))
        self.presentViewController(actionSheet, animated: true, completion: nil)
    }
    
    struct Sections {
        
        static let Phones = 0
        static let Altel = 1
        static let Megaline = 2
        static let idTvOnline = 3
        static let idPhone = 4
        
        static let Count = 5
    }
    
    func sendRequestRemoveIDTV(device : Device) {
        self.processRequest(true)
        Facade.sharedInstance().removeIDTV(device, onError: { (errorString) in
            AlertViewUtil.showAlert(errorString)
            }, onSuccess: { (successString) in
                AlertViewUtil.showAlert(successString)
                self.getDevices()
            }, onComplete: {
                self.processRequest(false)
        })
    }
}

