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

import Foundation
//import SwiftyJson

extension Facade {
    func devicesByExtractingServices(deviceParam: Device) -> [Device] {
        var devices:[Device] = []
        if deviceParam.deviceServices.count == 0 {
            let device = Device(deviceGroupName: deviceParam.deviceGroupName, connectTypeId: deviceParam.connectTypeId, connectTypeName: deviceParam.connectTypeName, tariffPlanName: deviceParam.connectTypeName, device: deviceParam.device, phone: deviceParam.phone, linkId: deviceParam.linkId)
            if deviceParam.type == .IDTV {
                device.type = .IDTV
            }
            devices.append(device)
        } else {
            for deviceService in deviceParam.deviceServices {
                let lowerCasedTariffPlanName = deviceService.tariffPlanName!.lowercaseString
                let device = Device(deviceGroupName: deviceParam.deviceGroupName, connectTypeId: deviceParam.connectTypeId, connectTypeName: deviceParam.connectTypeName, tariffPlanName: deviceService.tariffPlanName, device: deviceParam.device, phone: deviceParam.phone, linkId: deviceParam.linkId)
                if lowerCasedTariffPlanName.containsString("megaline") || lowerCasedTariffPlanName.containsString("id net")
                    || device.deviceGroupName!.lowercaseString.containsString("mgl_ip") {
                    device.type = DeviceContextMenu.TypeHasInternetSettings
                } else {
                    
                    device.type = DeviceContextMenu.TypeHasNoSettings
                    
                }
                if deviceParam.type == .IDTV {
                    device.type = .IDTV
                }
                
                devices.append(device)
            }
        }
        return devices
    }
    
    func createIDTV(connectTypeId : String, onError: String -> Void, onSuccess: String -> Void, onComplete:() -> Void) {
        let parameters = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!,
            "in_connect_type_id": connectTypeId,
            ] as [String : AnyObject]
        
        request(Router.CreateIDTV(parameters)).responseSwiftyJSON { (req, resp, json, error) in
            Router.globalLog.debug(req)
            Router.globalLog.debug(json)
            
            if let error = error {
                Router.globalLog.error(error.debugDescription)
                onError(error.localizedDescription)
            } else {
                if let error = json["error"].dictionary {
                    Router.globalLog.error(error.debugDescription)
                    onError("\(error.description)")
                } else if let error = json["error"].string {
                    Router.globalLog.error(error.debugDescription)
                    onError(error)
                } else {
                    
                    Router.globalLog.debug(resp)
                    onSuccess(json["msg"].string!)
                }
            }
            onComplete()
        }
    }
    
    func removeIDTV(device : Device, onError: String -> Void, onSuccess: String -> Void, onComplete:() -> Void) {
        let parameters = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!,
            "in_connect_type_id": device.connectTypeId!,
            "device" : device.device!,
            ] as [String : AnyObject]
        
        request(Router.RemoveIDTV(parameters)).responseSwiftyJSON { (req, resp, json, error) in
            Router.globalLog.debug(req)
            Router.globalLog.debug(json)
            if let error = error {
                Router.globalLog.error(error.debugDescription)
                onError(error.localizedDescription)
            } else {
                if let error = json["error"].dictionary {
                    Router.globalLog.error(error.debugDescription)
                    onError("\(error.description)")
                } else if let error = json["error"].string {
                    Router.globalLog.error(error.debugDescription)
                    onError(error)
                } else {
                    Router.globalLog.debug(resp)
                    onSuccess(json["msg"].string!)
                }
            }
            onComplete()
        }
    }
    
    func getListIDTVPlans(onError: String -> Void, onSuccess: [IDTVPlan] -> Void, onComplete:() ->  Void) {
        let parameters = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!,
            ] as [String : AnyObject]
        
        request(Router.ListIDTVPlans(parameters)).responseSwiftyJSON { (req, resp, json, error) in
            Router.globalLog.debug(req)
            Router.globalLog.debug(json)
            if let error = error {
                Router.globalLog.error(error.debugDescription)
                onError(error.localizedDescription)
            } else {
                if let error = json["error"].dictionary {
                    Router.globalLog.error(error.debugDescription)
                    onError("\(error.description)")
                } else if let error = json["error"].string {
                    Router.globalLog.error(error.debugDescription)
                    onError(error)
                } else {
                    Router.globalLog.debug(resp)
                    var plans : [IDTVPlan] = []
                    for subJson in json.arrayValue {
                        let plan = IDTVPlan(json: subJson)
                        plans.append(plan)
                    }
                    onSuccess(plans)
                }
            }
            onComplete()
        }
        
        
    }
    
    func getMegogo(onError: String -> Void, onSuccess: String -> Void, onComplete:() ->  Void) {
        let parameters = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!,
            ] as [String : AnyObject]
        
        request(Router.Megogo(parameters)).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
            Router.globalLog.debug(req)
            Router.globalLog.debug(json)
            if let error = error {
                Router.globalLog.error(error.debugDescription)
                onError(error.localizedDescription)
            } else {
                Router.globalLog.debug(resp)
                if let error = json["error"].dictionary {
                    Router.globalLog.error(error.debugDescription)
                    onError("\(error.description)")
                } else if let error = json["error"].string {
                    Router.globalLog.error(error.debugDescription)
                    onError(error)
                } else {
                    let link = json["link"]
                    if (link != nil) {
                        onSuccess(link.string!)
                    } else {
                        onSuccess("")
                        /*onSuccess("http://telecom.kz/api/get_bill_history.pdf?token=\(Facade.accessToken!)&client_id=\(Facade.clientId!)&period_id=11")*/
                    }
                }
            }
            onComplete()
        })
    }
    
    func getDevices(onError: String -> Void, onSuccess: [Device] -> Void, onComplete: () -> Void) {
        let parameters = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!,
            ] as [String: AnyObject]
        
        request(Router.Devices(parameters)).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
            Router.globalLog.debug(req)
            Router.globalLog.debug(json)
            if let error = error {
                Router.globalLog.error(error.debugDescription)
                onError(error.localizedDescription)
            } else {
                Router.globalLog.debug(resp)
                if let error = json["error"].dictionary {
                    Router.globalLog.error(error.debugDescription)
                    onError("\(error.description)")
                } else if let error = json["error"].string {
                    Router.globalLog.error(error.debugDescription)
                    onError(error)
                } else {
                    var devices:[Device] = []
                    for subJson in json.arrayValue {
                        let device = Device(json: subJson)
                        if (device.isIdTV()) {
                            for subSubJson in subJson["services"].arrayValue {
                                let idTVDevice = Device(json: subSubJson)
                                idTVDevice.type = .IDTV
                                devices.append(idTVDevice)
                            }
                        } else {
                            devices.append(device)
                        }
                        
                    }
                    var parsedDevices:[Device] = []
                    for device in devices {
                        parsedDevices.appendContentsOf(self.devicesByExtractingServices(device))
                    }
                    
                    onSuccess(parsedDevices)
                }
            }
            onComplete()
        })
    }
    
    func getAccountServices(onSuccess: AccountServices -> Void, onError: String -> Void, onComplete: () -> Void) {
        
        let parameters = [
            "access_token": Facade.accessToken!,
            "client_id": Facade.clientId!,
            "server_id": Facade.serverId!,
            "abonent_id": Facade.accountId!,
            ] as [String: AnyObject]
        
        request(Router.GetAccountServices(parameters)).responseSwiftyJSON { (req, resp, json, error) in
            
            onComplete()
            
            Router.globalLog.debug(resp)
            Router.globalLog.debug(json)
            
            guard let value = AccountServices.decode(json.dictionaryObject!) else {
                let errorCode = json["error_code"].int
                if errorCode == 3 {
                    onError(json["error"].string!)
                } else {
                    onError("Something went wrong")
                }
                return
            }
            onSuccess(value)
        }
    }
}
