//
//  GMSScreenSharing.swift
//  GMS Sample
//
//  Created by Jeffrey Culbert on 5/11/15.
//  Copyright (c) 2015 Genesys. All rights reserved.
//

import Foundation
import UIKit

class GMSScreenSharing: NSObject {
    
    private var view: UIView?
    
    dynamic var isOn = false
    dynamic var serviceId = "Not Set"
    dynamic var accessCode = "Not Set"
    dynamic var error: Error?
    
    var timer: Timer?
    
    override init() {
    }
    
    func startSharingWithServiceName(serviceName: String, view: UIView) {
        self.view = view
        
        error = nil
        accessCode = "Requesting..."
        isOn = true
        let params = ["account_id": "1234"]
        GMSUtil.submitRequest(withPath: "/1/service/" + serviceName, method: "POST", params: params, headers: nil, responseBlock: {
            
            (responseDict: [AnyHashable: Any]?, _error: Error?) -> Void in
            if self.isOn { // Ignore response if stop was requested while request was in progress
                self.error = _error
                if self.error == nil {
                    if let id: AnyObject = responseDict![NSString(string: "_id")] as AnyObject? {
                        self.serviceId = id as! String
                    }
                    else {
                        self.error = self.createErrorWithDescription(desc: "Error parsing _id from GMS response", code: 1)
                    }
                    if let code: AnyObject = responseDict![NSString(string: "_access_code")] as AnyObject? {
                        self.accessCode = code as! String
                    }
                    else {
                        self.error = self.createErrorWithDescription(desc: "Error parsing _access_code from GMS response", code: 2)
                    }
                }
                
                if self.error == nil {
                    self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: "sendScreen", userInfo: nil, repeats: true)
                }
                else {
                    self.serviceId = ""
                    self.accessCode = "Error"
                    self.isOn = false
                }
            }
        })
    }
    
    func stopSharing() {
        error = nil
        accessCode = "Not Set"
        isOn = false
        if self.timer != nil {
            self.timer!.invalidate()
            self.timer = nil
        }
    }
    
    func sendScreen() {
        
        UIGraphicsBeginImageContext(view!.bounds.size)
        view!.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        var params = [NSObject : NSObject]()
        params[NSString(string: "screen")] = UIImagePNGRepresentation(image!)! as NSObject?
        
        GMSUtil.submitRequest(withPath: "/1/service/" + serviceId + "/storage", method: "POST", params: params, headers: nil, completionBlock: nil)
    }
    
    private func createErrorWithDescription(desc: String, code: Int) -> NSError {
        var userInfo: [NSObject: AnyObject] = [NSObject: AnyObject]()
        userInfo[NSString(string: NSLocalizedDescriptionKey)] = NSString(string: desc)
        
        return NSError(domain: "GMSScreenSharing", code: code, userInfo: userInfo)
    }
}

