import Foundation
import Alamofire
import WowonderMessengerSDK

class UserManager {
    
    static let instance = UserManager()
    
    func authenticateUser(UserName: String, Password: String, DeviceId: String, completionBlock: @escaping (_ Success: LoginModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.username: UserName,
            API.Params.password: Password,
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.ios_m_device_id : DeviceId
        ]
        print("params >>>>> ", params)
        let urlString = API.AUTH_Constants_Methods.LOGIN_API
        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 {
                    let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try? JSONDecoder().decode(LoginModel.self, from: data!)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == "400" {
                        let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                        let result = try? JSONDecoder().decode(ErrorModel.self, from: data!)
                        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!)
                        completionBlock(nil, nil, result, nil)
                    }
                }
            } else {
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
    func RegisterUser(first_name: String, last_name: String, Email: String, UserName: String, DeviceId: String, Password: String, ConfirmPassword: String, gender: String, completionBlock: @escaping (_ Success: RegisterModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.first_name: first_name,
            API.Params.last_name: last_name,
            API.Params.username: UserName,
            API.Params.email: Email,
            API.Params.password: Password,
            API.Params.confirm_password: ConfirmPassword,
            API.Params.server_key: API.SERVER_KEY.Server_Key,
            API.Params.gender: gender,
            API.Params.ios_m_device_id : DeviceId
        ]
        print("params >>>>> ", params)
        let urlString = API.AUTH_Constants_Methods.REGISTER_API
        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 {
                    let data = try? JSONSerialization.data(withJSONObject: res, options: [])
                    let result = try? JSONDecoder().decode(RegisterModel.self, from: data!)
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == API.ERROR_CODES.E_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 == API.ERROR_CODES.E_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 forgetPassword(Email: String, completionBlock: @escaping (_ Success: ForgetPasswordModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.email: Email,
            API.Params.server_key: API.SERVER_KEY.Server_Key
        ]
        print("params >>>>> ", params)
        let urlString = API.AUTH_Constants_Methods.FORGETPASSWORD_API
        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(ForgetPasswordModel.self, from: data!)
                    print("Success = \(result?.apiStatus ?? 0)")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == API.ERROR_CODES.E_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 == API.ERROR_CODES.E_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 socialLogin(Provider: String, AccessToken: String, GoogleApiKey: String?, completionBlock: @escaping (_ Success: SocialLoginModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        var params = [String: String]()
        if Provider == API.SOCIAL_PROVIDERS.FACEBOOK {
            params = [
                API.Params.provider: Provider,
                API.Params.access_token: AccessToken,
                API.Params.server_key: API.SERVER_KEY.Server_Key
            ]
        } else {
            params = [
                API.Params.provider: Provider,
                API.Params.access_token: AccessToken,
                API.Params.server_key: API.SERVER_KEY.Server_Key,
                // API.Params.Google_Key : GoogleApiKey
            ] as! [String : String]
        }
        print("params >>>>>", params)
        let urlString = API.AUTH_Constants_Methods.SOCIAL_LOGIN_API
        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(SocialLoginModel.self, from: data)
                    print("Success = \(result.api_status ?? 0)")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == API.ERROR_CODES.E_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 == API.ERROR_CODES.E_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 deleteUser(sessionToken: String, password: String, completionBlock: @escaping (_ Success: ApiMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.password: password,
            API.Params.server_key: API.SERVER_KEY.Server_Key
        ]
        print("params >>>>> ", params)
        let urlString = API.AUTH_Constants_Methods.DELETE_USER_API + sessionToken
        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(ApiMessageModel.self, from: data)
                    print("Success = \(result.api_status ?? 0)")
                    completionBlock(result, nil, nil, nil)
                } else {
                    let apiStatusString = apiStatus as? String
                    if apiStatusString == API.ERROR_CODES.E_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 == API.ERROR_CODES.E_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)
            }
        }
    }
    
}
