import Foundation
import Alamofire
import WowonderMessengerSDK

class SettingsManager {
    
    static let instance = SettingsManager()
    
    func updateUserProfile(session_Token: String, first_name: String, last_name: String, about: String, facebook: String, twitter: String, instagram: String, vk: String, youtube: String, working: String, school: String, country_id: String, phone_number: String, website: String, relationship_id: String, completionBlock: @escaping (_ Success: ApiMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.first_name : first_name,
            API.Params.last_name : last_name,
            API.Params.about : about,
            API.Params.facebook : facebook,
            API.Params.twitter : twitter,
            API.Params.instagram : instagram,
            API.Params.vk : vk,
            API.Params.youtube : youtube,
            API.Params.working: working,
            API.Params.school : school ,
            API.Params.country_id : country_id,
            API.Params.phone_number : phone_number,
            API.Params.website : website,
            API.Params.relationship: relationship_id
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.Settings_Methods.UPDATE_USER_PROFILE_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(ApiMessageModel.self, from: data!)
                    print("Success = \(result?.message ?? "")")
                    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 updateAboutMe(session_Token: String, aboutme: String, completionBlock: @escaping (_ Success: ApiMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.about : aboutme,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.Settings_Methods.UPDATE_USER_PROFILE_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(ApiMessageModel.self, from: data)
                    print("Success = \(result.message ?? "")")
                    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 updateMyAccount(session_Token: String, username: String, email: String, birthday: String, gender: String, completionBlock: @escaping (_ Success: ApiMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.username : username,
            API.Params.email : email,
            API.Params.birthday: birthday,
            API.Params.gender : gender
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.Settings_Methods.UPDATE_USER_PROFILE_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(ApiMessageModel.self, from: data)
                    print("Success = \(result.message ?? "")")
                    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 updatePassword(session_Token: String, currentPassword: String, newPassword: String, completionBlock: @escaping (_ Success: ApiMessageModel?, _ AuthError: ErrorModel?,_ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.current_password : currentPassword,
            API.Params.new_password : newPassword,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.Settings_Methods.UPDATE_USER_PROFILE_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(ApiMessageModel.self, from: data)
                    print("Success = \(result.message ?? "")")
                    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 updateUserDataWithImage(session_Token: String, avatar_data: Data?, first_name: String, last_name: String, about: String, facebook: String, twitter: String, instagram: String, vk: String, youtube: String, working: String, school: String, country_id: String, phone_number: String, website: String, relationship_id: String, completionBlock: @escaping (_ Success: ApiMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.server_key : API.SERVER_KEY.Server_Key,
            API.Params.first_name : first_name,
            API.Params.last_name : last_name,
            API.Params.about : about,
            API.Params.facebook : facebook,
            API.Params.twitter : twitter,
            API.Params.instagram : instagram,
            API.Params.vk : vk,
            API.Params.youtube : youtube,
            API.Params.working: working,
            API.Params.school : school ,
            API.Params.country_id : country_id,
            API.Params.phone_number : phone_number,
            API.Params.website : website,
            API.Params.relationship: relationship_id
        ] as [String : Any]
        print("params >>>>>", params)
        let urlString = API.Settings_Methods.UPDATE_USER_PROFILE_API + session_Token
        print("urlString >>>>> ", urlString)
        let headers: HTTPHeaders = [
            "Content-type": "multipart/form-data"
        ]
        AF.upload(multipartFormData: { (multipartFormData) in
            for (key, value) in params {
                multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
            }
            if let avatarData = avatar_data {
                multipartFormData.append(avatarData, withName: "avatar", fileName: "avatar.jpg", mimeType: "image/png")
            }
            /*if let coverData = cover_data {
                multipartFormData.append(coverData, withName: "cover", fileName: "cover.jpg", mimeType: "image/png")
            }*/
        }, to: urlString, usingThreshold: UInt64.init(), method: .post, headers: headers).responseJSON(completionHandler: { (response) in
            print("Succesfully uploaded")
            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.message ?? "")")
                    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 updateTwoStepVerification(session_Token: String, type: String, completionBlock: @escaping (_ Success: ApiMessageModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.two_factor: type,
            API.Params.server_key : API.SERVER_KEY.Server_Key
        ] as [String : Any]
        print("params >>>>> ", params)
        let urlString = API.Settings_Methods.UPDATE_USER_PROFILE_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(ApiMessageModel.self, from: data)
                    print("Success = \(result.message ?? "")")
                    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 updatePrivacy(key: String, value: String, completionBlock: @escaping (_ Success: UpdateUserModel?, _ AuthError: ErrorModel?, _ ServerKeyError: ServerKeyErrorModel?, Error?) -> () ) {
        let params = [
            API.Params.server_key: API.SERVER_KEY.Server_Key,
            key: value
        ] as [String : Any]
        print("params >>>>> ", params)
        let sessionToken = AppInstance.instance.sessionId ?? ""
        let urlString = API.Settings_Methods.UPDATE_USER_PROFILE_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] {
                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(UpdateUserModel.self, from: data!)
                    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(response.error?.localizedDescription ?? "")
                completionBlock(nil, nil, nil, response.error)
            }
        }
    }
    
}
