//
//  WeatheManager.swift
//  WoWonderiOS
//
//  Created by UnikApp on 20/01/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import UIKit
import Alamofire
import Foundation
import WowonderMessengerSDK

class WeatherManager {
    
    static var sharedInstance = WeatherManager()
    
    func weatherForecast(latitude: Double, longitude: Double, completionBlock: @escaping(_ Success: WeatherModel?, _ AuthError: WeatherErrorModel?, Error?) -> ()) {
        let params = [
            "key" : ControlSettings.weatherApiKey,
            "q": "\(latitude),\(longitude)"
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = "http://api.weatherapi.com/v1/forecast.json?"
        print("urlString >>>>> ", urlString)
        AF.request(urlString, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
            if let res = response.value as? [String: Any] {
                if let error = res["error"] as? [String: Any] {
                    let data = try! JSONSerialization.data(withJSONObject: error, options: [])
                    let result = try! JSONDecoder().decode(WeatherErrorModel.self, from: data)
                    completionBlock(nil, result, nil)
                } else {
                    do {
                        let data = try JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try JSONDecoder().decode(WeatherModel.self, from: data)
                        completionBlock(result, nil, nil)
                    } catch {
                        completionBlock(nil, nil, error)
                    }
                }
            } else {
                completionBlock(nil, nil, response.error)
            }
        }
    }
    
}
