import Foundation
import Alamofire
import WowonderMessengerSDK

class SearchManager {
    
    static let instance = SearchManager()
    
    func searchUser(session_Token: String, country: String, status: String, verified: String, filterByAge: String, ageFrom: String, ageTo: String, search_Key: String, gender: String, completionBlock: @escaping (_ Success: SearchModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.gender : gender,
            API.Params.country : country,
            API.Params.status : status,
            API.Params.verified : verified,
            API.Params.filterbyage : filterByAge,
            API.Params.age_from : ageFrom,
            API.Params.age_to : ageTo,
            API.Params.search_key : search_Key,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.Search_Methods.SEARCH_USER_API + session_Token
        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] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try? JSONDecoder().decode(SearchModel.self, from: data!)
                    print("Success = \(result?.users ?? [])")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try? JSONDecoder().decode(ErrorModel.self, from: data!)
                        print("AuthError = \(result?.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try? JSONDecoder().decode(ServerKeyErrorModel.self, from: data!)
                        print("AuthError = \(result?.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func searchUserByFilter(session_Token: String, status: String, distance: String, gender: String, relationships: String, completionBlock: @escaping (_ Success: SearchModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.gender : gender,
            API.Params.status : status,
            API.Params.distance : distance,
            "relationships": relationships,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.Search_Methods.SEARCH_USER_API + session_Token
        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] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try? JSONDecoder().decode(SearchModel.self, from: data!)
                    print("Success = \(result?.users ?? [])")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try? JSONDecoder().decode(ErrorModel.self, from: data!)
                        print("AuthError = \(result?.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try? JSONDecoder().decode(ServerKeyErrorModel.self, from: data!)
                        print("AuthError = \(result?.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func searchForwardUser(session_Token: String, search_Key: String, completionBlock: @escaping (_ Success: SearchModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.search_key : search_Key,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.Search_Methods.SEARCH_USER_API + session_Token
        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] {
                print("Response = \(res)")
                guard let apiStatus = res["api_status"] else { return }
                if apiStatus is Int {
                    print("apiStatus Int = \(apiStatus)")
                    let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try! JSONDecoder().decode(SearchModel.self, from: data)
                    print("Success = \(result.users ?? [])")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        print("apiStatus String = \(apiStatus)")
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, result, nil, nil)
                    } else if apiStatusString == "404" {
                        let data = try! JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try! JSONDecoder().decode(ServerKeyErrorModel.self, from: data)
                        print("AuthError = \(result.errors?.error_text ?? "")")
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                print("error = \(response.error?.localizedDescription ?? "")")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
}
