//
//  ViewController.swift
//  Chat Application 1.1
//
//  Created by Avaya on 23/09/2016.
//  Copyright © 2016 Avaya. All rights reserved.
//

import UIKit
import SwiftyJSON

class ViewController: UIViewController{
    
    let routePoint = ""
    let workFlow = ""
    let workRequestId = ""
    let authKey = ""
    let chatUtils = RequestChatUtils()
    let jsonUtils = JSONUtils()
    var ewtResponse: String?
    var transcript = false
    var connectionData = RequestChatData()
    var attributes : [String]?
    var alertInput = [String]()
    var cc_address: String?
    var coBrowse_address : String?
    var ewt_address : String?
    var addressDictionary  : [String:String]?
    var attributesList : [String]?
    var requestChatRequest: String?
    var ewt: String?
    let stored = UserDefaults.standard
    
    
    @IBOutlet weak var chatButton: UIButton!
    @IBOutlet weak var backgroundImage: UIImageView!
    @IBOutlet weak var popoverEWTLabel: UILabel!
    
    @IBAction func settings() {
        self.performSegue(withIdentifier: "settingSegue", sender: self)
    }
    
    
    @IBAction func ChatButton() {
        self.ewtAlert(ewt: ewt ?? "")
        requestChatAlert()
        
    }

    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
            if(segue.identifier == "chatSegue"){
            let chatController: ChatViewController = segue.destination as! ChatViewController
            chatController.chatRequest = requestChatRequest!
            chatController.url = cc_address!
        }
    }
    
    
    override func viewDidLoad() {
        var loadResult = true
        var urlDictionary = [String: String]()
        if stored.string(forKey: "customerURL") != nil {
            
            let temp: String = stored.string(forKey: "customerURL")!
            urlDictionary["ccURL"] = temp;
        }
        else{
            loadResult = false
        }
        
        if stored.string(forKey: "ewtURL") != nil {
            
            let temp : String = stored.string(forKey: "ewtURL")!
            urlDictionary["ewtURL"] = temp;
        }
        else{
            loadResult = false
        }
        
//        if stored.string(forKey: "coBrowseURL") != nil {
//            
//            let temp : String = stored.string(forKey: "coBrowseURL")!
//            urlDictionary["coBrowseURL"] = temp;
//        }
//        else{
//            loadResult = false
//        }
        
        if stored.array(forKey: "attributes")?.count ?? 0 > 0 {

            let attrStored : [String] = stored.array(forKey: "attributes") as! [String]
            attributesList = attrStored
        }
        else{
            loadResult = false
        }
        if loadResult {
            addressDictionary = urlDictionary
            fillInVariables()
        }
        chatButton.isHidden = !loadResult
    }
    
    override func viewDidAppear(_ animated: Bool) {
        fillInVariables()
    }
    
    func fillInVariables() {
        
//        if let cobrowse_addr = addressDictionary?["coBrowseURL"]{
//            print(cobrowse_addr)
//            coBrowse_address = cobrowse_addr
//        }
        if let ewt_addr = addressDictionary?["ewtURL"]{
                let url = ewt_addr+"/services/CustomerControllerService/gila/ewt/request"
                print(url)
                
                //TODO - build EWT message here
                let map = getEWTFormattedAttributes()
                let json = buildEWTRequest(map: map)
                // print(json)
                sendRestRequest(uri: url, json)
        }
        
        if let cc_addr = addressDictionary?["ccURL"]{
            
            print(cc_addr)
            cc_address = cc_addr
            print("CC_address \(String(describing: cc_address))")
        }
    }
    
    func sendRestRequest(uri: String, _ message: String){
        
//        let url = NSURL(string: uri)
//        let request = NSMutableURLRequest(url: url! as URL)
//        request.httpBody = Data.init(base64Encoded: message)
        //{"serviceMap":{
//        "1":{
//        "attributes":{"Channel":["Chat"],"Location":["Inhouse"]}, "priority":5
//         }
//
//    }
//
//}
        let session = URLSession.shared
        let request = NSMutableURLRequest(url: NSURL(string: uri)! as URL)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        var params :[String: Any]?
        let map = getEWTFormattedAttributes()
        params = ["attributes" : map, "priority" : "1"]
        var temp :[String: Any]?
        temp = ["1" : params!]
        var jsonRequest :[String: Any]?
        jsonRequest = ["serviceMap": temp!]
        
        do{
            request.httpBody = try JSONSerialization.data(withJSONObject: jsonRequest!, options: JSONSerialization.WritingOptions())
                    let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
                        if let response = response {
                            let nsHTTPResponse = response as! HTTPURLResponse
                            let statusCode = nsHTTPResponse.statusCode
                            print ("status code = \(statusCode)")
                        }
                        if let error = error {
                            print ("\(error)")
                        }
                        if let data = data {
                            do{
                                let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
                                print ("data = \(jsonResponse)")
                                    let dict = jsonResponse as? [String: AnyObject]
                                    let ewt = dict?["serviceMetricsResponseMap"] as? [String: AnyObject]
                                    let temp = ewt?["1"] as? [String: AnyObject]
                                    let a = temp?["metrics"] as? [String: String]
                                    if let ewt = a?["EWT"] {
                                        self.ewt = ewt
                                        print("EWT: \(ewt)")
                                    } else {
                                        self.ewt = "0"
                                        print("EWT: 0")
                                    }
                            }catch _ {
                                print ("OOps not good JSON formatted response")
                            }
                        }
                    })
                    task.resume()
                }catch _ {
                    print ("Oops something happened buddy")
                }
        self.chatButton.isHidden = false
    }
    
    
 
    
    func buildEWTRequest(map: Dictionary<String,[String]>) -> String{
        
        let smPriority = ServiceMapPriority()
        
        smPriority.priority = 1
        smPriority.attributes = map
        let smContainer = ServiceMapContainer()
        smContainer.serviceMap!["1"] = smPriority
        
        
        let json = smContainer.toJSONString(prettyPrint: true)
        print(json ?? "")
        
        return json!
    }
    
    func getEWTFormattedAttributes() -> Dictionary<String,[String]>{
        
        var categorySet = Set<String>()
        var attributeSet = Set<String>()
        var attributeMap = [String:[String]]()
        
        attributeMap["Channel"] = ["Chat"]
        if let attributes = attributesList{
            print(attributes)
            
            for item in attributes{
                let splitter = item.split(separator: ".")
                let category : String = String(splitter.first!)
                let attribute : String = String(splitter.last!)
                
                //append attribute to existing category
                if categorySet.contains(category){
                    print("Category exists \(category)")
                    if !attributeSet.contains(attribute) {
                        print("attribute does not exist in category. adding \(attribute) to \(category)")
                        attributeSet.insert(attribute)
                        attributeMap[category]?.append(attribute)
                    }
                }
                else{
                    print("Else, adding category: \(category) AND attribute: \(attribute) to Map ")
                    categorySet.insert(category)
                    var tempList = [String]()
                    tempList.append(attribute)
                    attributeMap[category] = tempList
                    
                }
                
            }
        }
        
        return attributeMap
    }
    
    
    
    func requestChatAlert(){
        print("requestChatAlert()")
        
        //declaring the alert dialog for the chat request
        let alert: UIAlertController = UIAlertController(title: "", message: "Request a Chat", preferredStyle: .alert)
        alert.view.autoresizesSubviews = true
        alert.view.addSubview(self.addSwitch())
        
        //alert.view.addSubview(self.addLabel())
        //textfields to request the name and email of the customer
        
        alert.addTextField( configurationHandler: { (textField) -> Void in
            textField.placeholder = "Your Name"
        })
        alert.addTextField (configurationHandler: { (textField) -> Void in
            textField.placeholder = "Someone@Some.thing"
            textField.keyboardType = UIKeyboardType.emailAddress
        })
        alert.addTextField { (textField) -> Void in
            textField.placeholder = "area -  353"
            textField.keyboardType = UIKeyboardType.numberPad
            
        }
        alert.addTextField { (textField) -> Void in
            textField.placeholder = "country - 011"
            textField.keyboardType = UIKeyboardType.numberPad
            
        }
        alert.addTextField { (textField) -> Void in
            textField.placeholder = "phone - 12345"
            textField.keyboardType = UIKeyboardType.numberPad
            
        }
        
        //extract the text from the alert text fields on "OK"
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action)-> Void in
            
            
            let name_tf = alert.textFields![0] as UITextField
            let email_tf = alert.textFields![1] as UITextField
            let phone_area = alert.textFields![2] as UITextField
            let phone_country = alert.textFields![3] as UITextField
            let phone_tf = alert.textFields![4] as UITextField
            let name = name_tf.text
            let email = email_tf.text
            let phoneArea = phone_area.text
            let phoneCountry = phone_country.text
            let phoneNo = phone_tf.text
            self.alertInput.append(name!)
            self.alertInput.append(email!)
            self.alertInput.append(phoneNo!)
            self.alertInput.append(phoneArea!)
            self.alertInput.append(phoneCountry!)
            
            self.requestChatRequest = self.buildChatRequestString(alert: self.alertInput)
            self.alertInput.removeAll()
            self.performSegue(withIdentifier: "chatSegue", sender: self)
            
        }))
        
        alert.addAction(UIAlertAction(title: "Close", style: .cancel, handler: { (action) -> Void in
            print("Dialog Canceled")
        }))
        
        self.present(alert, animated: true, completion: nil)
        
    }
    
    func addSwitch() -> UISwitch{
        
        let switchControl = UISwitch(frame: CGRect(x: 0,y: 0,width: 0,height: 60))
        switchControl.isOn = false
        switchControl.setOn(false,animated: false)
        switchControl.addSubview(self.addLabel())
        
        switchControl.addTarget(self, action: #selector(ViewController.switchValueDidChange), for: .valueChanged)
        return switchControl
        
    }
    
    func addLabel() -> UILabel{
        let label = UILabel(frame: CGRect(x: 60,y: 10,width: 200,height: 10))
        label.text = " Request Email Transcript?"
        label.font = label.font.withSize(10)
        return label
        
    }
    
    @objc func switchValueDidChange(sender: UISwitch!){
        if sender.isOn{
            transcript = true
            
        }
            
        else{
            transcript = false
        }
        
        print(transcript)
    }
    
    func ewtAlert(ewt: String){
        print("EWT \(ewt)")
        
        let doubNumber = Double(ewt)
        print(doubNumber ?? 0)
        let number: Int = Int(doubNumber ?? 0)
        print("number: \(number)")
        var message : String?
        var offerChat = false
        
        let  max = 6000 //aka 10 min
        
        if number >= 0 && number < max {
            let showTime: Int  = number/60
            
            if(showTime == 0 ){
                message = " An agent is available, do you want to Chat?"
            }
            else{
                message = "An Agent will be available in \(showTime) mins"
            }
            offerChat = true
        }
            
        else if number < 0 || number > max{
            offerChat = false
            message = "An agent is not currently available\nPlease try again later"
        }
            
        else{
            
            offerChat = true
            message = "Would you like to Chat?"
            
            
        }
        
        let alert: UIAlertController = UIAlertController(title: "Estimated Wait Time", message: message, preferredStyle: .alert)
        
        
        if offerChat{
            //extract the text from the alert text fields on "OK"
            alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action)-> Void in
                //get the request caht bject as JSON
                self.requestChatAlert()
            }))
            
            alert.addAction(UIAlertAction(title: "No", style: .destructive, handler: { (action) -> Void in
                
            }))
            
        }
            
        else{
            alert.addAction(UIAlertAction(title: "Dismiss", style: .destructive, handler: { (action) -> Void in
                self.chatButton.isHidden = true
            }))
        }
        
        self.present(alert, animated: true, completion: nil)
    }
    
    

    
    func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }
    
    func buildChatRequestString( alert: [String])->String{
        
        
        let name = alert[0]
        print("Name \(name)")
        let email = alert[1]
        let phoneNo = alert[2]
        let area = alert[3]
        let country = alert[4]
        var attributes: [String]?
        let authToken = ""
        
        
        print("Connection Data attribute size: \(connectionData.attributes?.count ?? 0)")
        if attributesList != nil{
            attributes = attributesList
        }
        else{
            attributes = [String]()
        }
        
        let customFields = CustomFields()
        customFields.title = "Title 1"
        customFields.value = "value 1"
        
        let customFieldsList : [CustomFields] = [customFields]
        
        let json =  self.chatUtils.buildRequestChatRequest(authToken: authToken, name: name, email: email, phoneNumber: phoneNo, area: area, country: country, attributes: attributes!, customFields: customFieldsList,transcript: transcript)
        
        return json
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    
    
    
}

