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

import Foundation
import UIKit

class MyServicesViewController : UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    var loadingIndicator : UIActivityIndicatorView?
    @IBOutlet var tableView: UITableView!
    let reuseCellIdentifier = "cell"
    var devices:[Device] = []
    var matchedLabel: UILabel?
    var selectedDeviceIndex:Int?
    var requestTryCount = 0
    var cellIndexWithoutSettings = 0
    
    func configureRightIndicator() {
        loadingIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
        loadingIndicator!.hidesWhenStopped = true
        loadingIndicator!.color = .whiteColor()
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: loadingIndicator!)
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        registerObservers()
        //configureRightIndicator()
        configureRightIDTVCreate()
        configureTableView()
        loadingIndicator?.startAnimating()
        self.requestTryCount = 0
        requestDevices()
        tableView.allowsSelection = true
    }
    
    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 registerObservers() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(MyServicesViewController.appDidBecomeActive), name: Notification.appDidBecomeActive, object: nil)
    }
    
    func appDidBecomeActive() {
        print("appDidBecomeActive")
        self.requestTryCount = 0
        requestDevices()
    }
    
    func showCreateIDTV(sender: UIBarButtonItem) {
        performSegueWithIdentifier("idtv_create", sender: nil)
    }
    
    func requestDevices() {
        Facade.sharedInstance().getDevices({ errorMessage -> Void in
            if self.requestTryCount < 3 {
                self.requestTryCount += 1
                self.requestDevices()
            } else {
                Facade.sharedInstance().getAltelDevices({ errorMessage -> Void in
                    AlertViewUtil.showIncorrectAlert(errorMessage)
                    }, onSuccess: { (devices) -> Void in
                        self.devices.appendContentsOf(devices)
                        self.tableView.reloadData()
                    }, onFinish: {
                        self.loadingIndicator?.stopAnimating()
                })
            }
            }, onSuccess: { services -> Void in
                self.devices = services
                Facade.sharedInstance().getAltelDevices({ errorMessage -> Void in
                    AlertViewUtil.showIncorrectAlert(errorMessage)
                    }, onSuccess: { (devices) -> Void in
                        self.devices.appendContentsOf(devices)
                        self.devices.sortInPlace({ (d1, d2) -> Bool in
                            var result = true
                            if d1.type == DeviceContextMenu.TypeHasNoSettings {
                                
                                
                                result = false;
                            }
                            return result
                        })
                        
                        var index = 0
                        for var device in self.devices {
                            if (device.type == DeviceContextMenu.TypeHasNoSettings) {
                                self.cellIndexWithoutSettings = index
                                break
                            }
                            index = index + 1
                        }
                        
                        self.tableView.reloadData()
                        self.sendRequestMegogo()
                    }, onFinish: {
                        self.loadingIndicator?.stopAnimating()
                })
            }, onComplete: {
        })
    }
    
    func sendRequestMegogo() {
        Facade.sharedInstance().getMegogo({ (errorString) in
            
            }, onSuccess: { (successString) in
                if (successString.characters.count > 0) {
                    let device = Device(deviceGroupName: "MEGOGO", connectTypeId: "", connectTypeName: "", tariffPlanName: "", device: "", phone: 0, linkId: "")
                    device.url = successString
                    device.type = .Megogo
                    self.devices.insert(device, atIndex: 0)
                    self.tableView.reloadData()
                } 
        }) {
            
        }
    }
    
    func sendRequestRemoveIDTV(device : Device) {
        self.processRequest(true)
        Facade.sharedInstance().removeIDTV(device, onError: { (errorString) in
            AlertViewUtil.showAlert(errorString)
            }, onSuccess: { (successString) in
                AlertViewUtil.showAlert(successString)
                self.devices.removeAtIndex(self.devices.indexOf({ (aDevice) -> Bool in
                    return aDevice.device?.compare(device.device!) == NSComparisonResult.OrderedSame
                })!)
                self.tableView.reloadData()
            }, onComplete: {
                self.processRequest(false)                
        })
    }
    
    override func processRequest(enabled: Bool) {
        super.processRequest(enabled)
        self.navigationItem.leftBarButtonItem?.enabled = !enabled
        self.view.userInteractionEnabled = !enabled
    }
    
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        guard let identifier = segue.identifier else { return }
        switch identifier {
        case "goToDeviceSettings":
            let vc = segue.destinationViewController as? DeviceSettingsViewController
            if let selectedDeviceIndex = selectedDeviceIndex {
                vc?.device = devices[selectedDeviceIndex]
            }
            break
        case "altelDetail":
            let vc = segue.destinationViewController as? DetalizationViewController
            if let selectedDeviceIndex = selectedDeviceIndex where devices[selectedDeviceIndex].device != nil {
                vc?.phone = devices[selectedDeviceIndex].device!
            }
            break
        case "publicWifi":
            let vc = segue.destinationViewController as? PublicWifiViewController
            if let selectedDeviceIndex = selectedDeviceIndex {
                vc?.device = devices[selectedDeviceIndex]
            }
            break
        case "subscribe_history":
            let vc = segue.destinationViewController as? SubscribeHistoryViewController
            if let selectedDeviceIndex = selectedDeviceIndex {
                vc?.device = devices[selectedDeviceIndex]
            }
            break
        case "active_sessions":
            let vc = segue.destinationViewController as? ActiveSessionsViewController
            if let selectedDeviceIndex = selectedDeviceIndex {
                vc?.device = devices[selectedDeviceIndex]
            }
            break
        default: break
        }
    }
    
    private func configureTableView() {
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 100
    }
    
    func detalization_touchUpInside(sender: AnyObject) {
        
        self.dismissViewControllerAnimated(true, completion: nil)
        performSegueWithIdentifier("altelDetail", sender: nil)
    }
    
    func changeNavbar() {
        self.navigationController?.navigationBar.setBackgroundImage(nil, forBarMetrics: UIBarMetrics.Default)
        navigationController?.navigationBar.shadowImage = nil
        self.navigationController?.navigationBar.barStyle = UIBarStyle.Default
        navigationController?.navigationBar.barTintColor = UIColor.whiteColor()
    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        localize()
        //    configureNavTitles()
        configureBlueNavbar()
        configureRightIDTVCreate()
    }
}

// UITableViewDataSource
extension MyServicesViewController {
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return devices.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseCellIdentifier, forIndexPath: indexPath) as! MyServicesCell
        cell.fillCell(devices[indexPath.row])
        if (indexPath.row >= cellIndexWithoutSettings) {
            cell.selectionStyle = .None
        }
        return cell
    }
    
}

// UITableViewDelegate
extension MyServicesViewController {
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        selectedDeviceIndex = indexPath.row
        let cell = tableView.cellForRowAtIndexPath(indexPath)
        cell!.selectionStyle = .None
        let device = devices[indexPath.row]
        if (device.type == DeviceContextMenu.IDTV) {
            let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
            actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
            let rootView = UIApplication.sharedApplication().keyWindow!.rootViewController!.view
            actionSheet.popoverPresentationController?.sourceView = rootView
            actionSheet.popoverPresentationController?.sourceRect = CGRect(origin: CGPoint(x: CGRectGetMidX(rootView.bounds), y: CGRectGetMidY(rootView.bounds)), size: CGSizeZero)
            actionSheet.addAction(UIAlertAction(title: LS("my_services_idtv_remove"), style: .Default, handler: { (alertAction) in
                self.sendRequestRemoveIDTV(device)
            }))
            actionSheet.addAction(UIAlertAction(title: LS("my_services_idtv_activation"), style: .Default, handler: { (alertAction) in
                AlertViewUtil.showAlert(LS("my_services_idtv_activationMessage"))
            }))
            actionSheet.addAction(UIAlertAction(title: LS("cancel"), style: .Cancel, handler: nil))
            
            UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(actionSheet, animated: true, completion: nil)
            
        } else
        if (device.type == DeviceContextMenu.Megogo) {
            let vc = KTWebViewController.init(url: device.url!)
            vc.title = "MEGOGO"
            showViewController((vc), sender: self)
            
            /*
             let vc: UIViewController? = UIViewController()
             vc?.title = "MEGOGO"
             let webView = UIWebView(frame: (vc?.view.frame)!)
             vc?.view.addSubview(webView)
             webView.scalesPageToFit = true*/
            
            //showViewController((vc)!, sender: self)
            //webView.loadRequest(NSURLRequest(URL: NSURL(string: device.url!)!))
        } else
            if devices[indexPath.row].type == DeviceContextMenu.TypeHasInternetSettings {
                
                let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
                
                actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
                let rootView = UIApplication.sharedApplication().keyWindow!.rootViewController!.view
                actionSheet.popoverPresentationController?.sourceView = rootView
                
                actionSheet.popoverPresentationController?.sourceRect = CGRect(origin: CGPoint(x: CGRectGetMidX(rootView.bounds), y: CGRectGetMidY(rootView.bounds)), size: CGSizeZero)
                
                actionSheet.addAction(UIAlertAction(title: LS("my_services.button.connect_history"), style: .Default, handler: { (alertAction) in
                    self.performSegueWithIdentifier("subscribe_history", sender: nil)
                    //        self.dismissViewControllerAnimated(true) { () -> Void in
                    //          self.performSegueWithIdentifier("subscribe_history", sender: nil)
                    //        }
                }))
                
                actionSheet.addAction(UIAlertAction(title: LS("my_services.button.active_sessions"), style: .Default, handler: { (alertAction) in
                    //        self.dismissViewControllerAnimated(true) { () -> Void in
                    self.performSegueWithIdentifier("active_sessions", sender: nil)
                    //        }
                }))
                
                actionSheet.addAction(UIAlertAction(title: LS("my_services.button.settings"), style: .Default, handler: { (alertAction) in
                    //        self.dismissViewControllerAnimated(true) { () -> Void in
                    self.performSegueWithIdentifier("goToDeviceSettings", sender: nil)
                    //        }
                }))
                
                actionSheet.addAction(UIAlertAction(title: LS("my_services.button.common_wifi"), style: .Default, handler: { (alertAction) in
                    //        self.dismissViewControllerAnimated(true) { () -> Void in
                    self.performSegueWithIdentifier("publicWifi", sender: nil)
                    //        }
                }))
                
                actionSheet.addAction(UIAlertAction(title: LS("cancel"), style: .Cancel, handler: nil))
                
                UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(actionSheet, animated: true, completion: nil)
                
                //      self.presentViewController(actionSheet, animated: true, completion: nil)
                
                //      MyServicesActionSheetContent.fillAndShow(MyActionSheetStyle.Square, presentingVC: self, closure: { (actionSheet) -> Void in
                //
                //        actionSheet.addButton(actionSheet.generateButton(LS("my_services.button.connect_history")), handler: { (button) -> Void in
                //          self.dismissViewControllerAnimated(true) { () -> Void in
                //            self.performSegueWithIdentifier("subscribe_history", sender: nil)
                //          }
                //        })
                //
                //        actionSheet.addButton(actionSheet.generateButton(LS("my_services.button.active_sessions")), handler: { (button) -> Void in
                //          self.dismissViewControllerAnimated(true) { () -> Void in
                //            self.performSegueWithIdentifier("active_sessions", sender: nil)
                //          }
                //        })
                //
                //        actionSheet.addButton(actionSheet.generateButton(LS("my_services.button.settings")), handler: { (button) -> Void in
                //          print("thirdButton_touchUpInside")
                //          self.dismissViewControllerAnimated(true) { () -> Void in
                //            self.performSegueWithIdentifier("goToDeviceSettings", sender: nil)
                //          }
                //        })
                //
                //        //        4
                //        actionSheet.addButton(actionSheet.generateButton(LS("my_services.button.common_wifi")), handler: { (button) -> Void in
                //          self.dismissViewControllerAnimated(true) { () -> Void in
                //            self.performSegueWithIdentifier("publicWifi", sender: nil)
                //          }
                //        })
                //        actionSheet.contentView.resizeToFitSubviews()
                //        actionSheet.contentViewHeight.constant = actionSheet.contentView.frame.height
                //        //        contentViewHeight.constant = contentView.frame.height
                //        
                //      })
                
            } else if devices[indexPath.row].type == DeviceContextMenu.AltelDevice {
                
                let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
                actionSheet.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection.init(rawValue: 0)
                actionSheet.popoverPresentationController?.sourceView = self.view
                actionSheet.addAction(UIAlertAction(title: LS("my_services.button.detalization"), style: .Default, handler: { (alertAction) in
                    //        self.dismissViewControllerAnimated(true) { () -> Void in
                    self.performSegueWithIdentifier("altelDetail", sender: nil)
                    //        }
                }))
                
                actionSheet.addAction(UIAlertAction(title: LS("cancel"), style: .Cancel, handler: nil))
                
                self.presentViewController(actionSheet, animated: true, completion: nil)
                
                //      MyServicesActionSheetContent.fillAndShow(MyActionSheetStyle.Square, presentingVC: self, closure: { (actionSheet) -> Void in
                //        actionSheet.addButton(actionSheet.generateButton(LS("my_services.button.detalization")), handler: { (button) -> Void in
                //          self.dismissViewControllerAnimated(true) { () -> Void in
                //            self.performSegueWithIdentifier("altelDetail", sender: nil)
                //          }
                //        })
                //        
                //      })
        }
    }
}

extension MyServicesViewController {
    override var localizedId: String {
        return "my_services"
    }
}
