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

import Foundation

extension Facade {
  func getTargetingList(params: [String: AnyObject], onSuccess: ([[String]]) -> Void, onError: (error: String) -> Void, onFinish: () -> Void) {
    request(Router.GetTargetingList(params)).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
      Router.globalLog.debug(req)
      Router.globalLog.debug(json)
      onFinish()
      if let error = error {
        Router.globalLog.error(error.debugDescription)
        onError(error: error.localizedDescription)
      } else {
        Router.globalLog.debug(resp)
        if let error = json["error"].dictionary {
          Router.globalLog.error(error)
          onError(error: "\(error.description)")
        } else if let error = json["error"].string {
          Router.globalLog.error(error)
          onError(error: error)
        } else {
          if json["success"].bool == true {
            if let list = json["list"].dictionaryObject as? [String: String] {
              var items:[[String]] = []
              for (key, value) in list {
                items.append([key, value])
              }
              items.sortInPlace({ (item1, item2) -> Bool in
                return item1[1].compare(item2[1]) == NSComparisonResult.OrderedAscending
              })
              onSuccess(items)
            } else if let list = json["list"].arrayObject as? [[String: String]] {
              var items:[[String]] = []
              for el in list {
                items.append([el["id"]!, el["name"]!])
              }
              items.sortInPlace({ (item1, item2) -> Bool in
                return item1[1].compare(item2[1]) == NSComparisonResult.OrderedAscending
              })
              onSuccess(items)
            } else if let list = json["list"].dictionaryObject as? [String:[String:String]] {
                var items:[[String]] = []
                for el in list {
                    let id = el.1["id"]
                    let name = el.1["name"]
                    items.append([id!, name!])
                
                    //items.append([el["id"] as! String, el["name"] as! String])
                }
                items.sortInPlace({ (item1, item2) -> Bool in
                    return item1[1].compare(item2[1]) == NSComparisonResult.OrderedAscending
                })
                onSuccess(items)
            }
        } else {
            Router.globalLog.error("getTargetingList error")
            onError(error: LS("error"))
          }
        }
      }
    })
  }
  
  func getSpecialOffers(params: [String: AnyObject], onSuccess: ([SpecialOffer]) -> Void, onError: (error: String) -> Void, onFinish: () -> Void) {
    request(Router.SpecialOffers(params)).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
      Router.globalLog.debug(req)
      Router.globalLog.debug(json)
      onFinish()
      if let error = error {
        Router.globalLog.error(error.debugDescription)
        onError(error: error.localizedDescription)
      } else {
        Router.globalLog.debug(resp)
        if let error = json["error"].dictionary {
          Router.globalLog.error(error)
          onError(error: "\(error.description)")
        } else if let error = json["error"].string {
          Router.globalLog.error(error)
          onError(error: error)
        } else {
          if json["success"].bool == true {
            var specialOffers: [SpecialOffer] = []
            let list = json["list"].arrayValue
            for subJson in list {
              specialOffers.append(SpecialOffer(json: subJson))
            }
            onSuccess(specialOffers)
          } else {
            Router.globalLog.error("getSpecialOffers error")
            onError(error: LS("error"))
          }
        }
      }
    })
  }

  func getFormType(onSuccess: ([FormType]) -> Void, onError: (error: String) -> Void, onFinish: () -> Void) {
    request(Router.GetFormType).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
      Router.globalLog.debug(req)
      Router.globalLog.debug(json)
      onFinish()
      if let error = error {
        Router.globalLog.error(error.debugDescription)
        onError(error: error.localizedDescription)
      } else {
        Router.globalLog.debug(resp)
        if let error = json["error"].dictionary {
          Router.globalLog.error(error)
          onError(error: "\(error.description)")
        } else if let error = json["error"].string {
          Router.globalLog.error(error)
          onError(error: error)
        } else {
          if let jsonArray = json.array {
            var formTypes: [FormType] = []
            for subJson in jsonArray {
              formTypes.append(FormType(json: subJson))
            }
            onSuccess(formTypes)
          } else {
            Router.globalLog.error("getFormType error")
            onError(error: LS("error"))
          }
        }
      }
    })
  }

  
  func callbackSend(params: [String: AnyObject], onSuccess: (String) -> Void, onError: (error: String) -> Void, onFinish: () -> Void) {
    request(Router.CallbackSend(params)).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
      Router.globalLog.debug(req)
      Router.globalLog.debug(json)
      onFinish()
      if let error = error {
        Router.globalLog.error(error.debugDescription)
        onError(error: error.localizedDescription)
      } else {
        Router.globalLog.debug(resp)
        if let error = json["error"].dictionary {
          Router.globalLog.error(error)
          onError(error: "\(error.description)")
        } else if let error = json["errors"].dictionary {
          Router.globalLog.error(error)
          onError(error: "\(error.description)")
        } else if let error = json["error"].string {
          Router.globalLog.error(error)
          onError(error: error)
        } else {
          if let msg = json["msg"].string {
            onSuccess(msg)
          } else {
            Router.globalLog.error("callbackSendError")
            onError(error: LS("error"))
          }
        }
      }
    })
  }
  
    func getGUID(params: [String: AnyObject], onSuccess: (String) -> Void, onError: (error: String) -> Void, onFinish: () -> Void) {
        request(Router.GetGUID(params)).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
            Router.globalLog.debug(req)
            Router.globalLog.debug(json)
            onFinish()
            if let error = error {
                Router.globalLog.error(error.debugDescription)
                onError(error: error.localizedDescription)
            } else {
                Router.globalLog.debug(resp)
                if let error = json["error"].dictionary {
                    Router.globalLog.error(error)
                    onError(error: "\(error.description)")
                } else if let error = json["error"].string {
                    Router.globalLog.error(error)
                    onError(error: error)
                } else {
                    if let msg = json["message"].string {
                        onSuccess(msg)
                    } else {
                        Router.globalLog.error("getGUID error")
                        onError(error: LS("error"))
                    }

                }
            }
        })
    }

    func getListServerId(onSuccess: ([ServerItem]) -> Void, onError: (error: String) -> Void, onFinish: () -> Void) {
        request(Router.GetLisetServerId).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
            Router.globalLog.debug(req)
            Router.globalLog.debug(json)
            onFinish()
            if let error = error {
                Router.globalLog.error(error.debugDescription)
                onError(error: error.localizedDescription)
            } else {
                Router.globalLog.debug(resp)
                if let error = json["error"].dictionary {
                    Router.globalLog.error(error)
                    onError(error: "\(error.description)")
                } else if let error = json["error"].string {
                    Router.globalLog.error(error)
                    onError(error: error)
                } else {
                    if let jsonItems = json.array {
                        var items: [ServerItem] = []
                        for subJson in jsonItems {
                            items.append(ServerItem(json: subJson))
                        }
                        onSuccess(items)
                    } else {
                        Router.globalLog.error("getOfferRegions error")
                        onError(error: LS("error"))
                    }
                }
            }
        })
    }

    
    
  func getOfferRegions(onSuccess: ([CallbackRegion]) -> Void, onError: (error: String) -> Void, onFinish: () -> Void) {
    request(Router.GetRegions).responseSwiftyJSON(completionHandler: { (req, resp, json, error) in
      Router.globalLog.debug(req)
      Router.globalLog.debug(json)
      onFinish()
      if let error = error {
        Router.globalLog.error(error.debugDescription)
        onError(error: error.localizedDescription)
      } else {
        Router.globalLog.debug(resp)
        if let error = json["error"].dictionary {
          Router.globalLog.error(error)
          onError(error: "\(error.description)")
        } else if let error = json["error"].string {
          Router.globalLog.error(error)
          onError(error: error)
        } else {
          if let regions = json.array {
            var callbackRegions: [CallbackRegion] = []
            for subJson in regions {
              callbackRegions.append(CallbackRegion(json: subJson))
            }
            onSuccess(callbackRegions)
          } else {
            Router.globalLog.error("getOfferRegions error")
            onError(error: LS("error"))
          }
        }
      }
    })
  }

}
