//
//  GifManager.swift
//  WoWonder
//
//  Created by Muhammad Haris Butt on 11/3/20.
//  Copyright © 2020 ScriptSun. All rights reserved.
//

import Foundation
import Alamofire
import WowonderMessengerSDK

class GIFManager {
    
    static let instance = GIFManager()
    
    func getTrendingGIF(limit: Int, completionBlock: @escaping (_ Success: GIFModel?, Error?) -> () ) {
        let params = [
            API.Params.api_key : "b9427ca5441b4f599efa901f195c9f58",
            API.Params.limit: limit,
            API.Params.rating: "g"
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GIF_API.GIF_TRENDING_API
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                let result = try! JSONDecoder().decode(GIFModel.self, from: data)
                completionBlock(result, nil)
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, response.error)
            }
        }
    }
    
    func getSearchGIF(limit: Int, search_key: String, completionBlock: @escaping (_ Success: GIFModel?, Error?) -> () ) {
        let params = [
            API.Params.api_key : "b9427ca5441b4f599efa901f195c9f58",
            API.Params.limit: limit,
            API.Params.rating: "g",
            API.Params.q: search_key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.GIF_API.GIF_SEARCH_API
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .get, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                let result = try! JSONDecoder().decode(GIFModel.self, from: data)
                completionBlock(result, nil)
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, response.error)
            }
        }
    }
    
}
