// // RecipientViewModel.swift // GMERemittance // // Created by Sujal on 12/27/17. // Copyright © 2017 Gobal Money Express Co. Ltd. All rights reserved. // import Foundation class RecipientViewModel: ModelExtension { let userId = UserDefaults.standard.object(forKey: "com.gmeremit.username") as? String private var cddTransferReasonList: [String] = [String] () private var cddTransferReasonValueList: [String] = [String] () private var cddStateList: [String] = [String]() private var cddStateValueList: [String] = [String]() private var cddDistrictList: [String] = [String]() private var cddDistrictValueList: [String] = [String]() private var cddRelationList: [String] = [String] () private var cddRelationValueList: [String] = [String] () private var countryList: [AgentCountryList] = [AgentCountryList] () private var cddCountryList: [String] = [String]() private var cddCountryFlag: [String] = [String] () private var cddCountryIdList: [String] = [String] () var recipientModel = AgentCountryList() var recipientCreatedUpdated: Box = Box(nil) var recipientListObtained: Box = Box(nil) var recipientDeleted: Box = Box(nil) var cddCountryListAvailable: Box = Box(nil) var cddListAvailable: Box = Box(nil) var recipientArray = [Recipient]() private var recipient: Recipient! private var newRecipient: Recipient! /** */ var recipientConnectionTimeOut: Box = Box(nil) var recipientDeletedTimeOut: Box = Box(nil) override init() { var reciepient = Recipient() reciepient.firstName = "" reciepient.lastName = "" reciepient.country = "" reciepient.state = "" reciepient.state = "" reciepient.stateId = "" reciepient.city = "" reciepient.address = "" reciepient.district = "" reciepient.districtId = "" reciepient.relation = "" reciepient.relationId = "" reciepient.mobileNumber = "" reciepient.email = "" reciepient.recipientId = "" reciepient.reason = "" reciepient.reasonId = "" reciepient.reason = "" reciepient.reasonId = "" reciepient.countryId = "" self.recipient = reciepient } init(recipient: Recipient) { self.recipient = recipient } /** To update first name - parameter firstName: first name */ func updateFirstName(firstName: String) { recipient.firstName = firstName } /** To update middle name - parameter middleName: middle name */ func updateMiddleName(middleName: String) { recipient.middleName = middleName } /** To update lasr name - parameter lastName: last name */ func updateLastName(lastName: String) { recipient.lastName = lastName } /** To update country - parameter country: country */ func updateCountry(country: String) { recipient.country = country } /** To update state - parameter state: state */ func updateState(state: String) { recipient.state = state } /** To update district - parameter district: district */ func updateDistrict(district: String) { recipient.district = district } /** To update city - parameter city: city */ func updateCity(city: String) { recipient.city = city } /** To update address - parameter address: address */ func updateAddress(address: String) { recipient.address = address } /** To update address - parameter address: address */ func updateRelation(relation: String) { recipient.relation = relation } /** To update mobile - parameter mobile: mobile */ func updateMobile(mobile: String) { recipient.mobileNumber = mobile } /** To update email - parameter email: email */ func updateEmail(email: String) { recipient.email = email } /** To update transferReason - parameter reason: transferReason */ func updateTransferReason(reason: String){ recipient.reason = reason } /** To get recipient details - returns: recipient detail info */ func getRecipientDetails() -> [String: String] { if recipient.email == nil { if recipient.middleName == nil { return ["firstName": recipient?.firstName ?? "", "lastName": recipient?.lastName ?? "", "city": recipient?.city ?? "", "state": recipient?.state ?? "", "address": recipient?.address ?? "", "country": recipient?.country ?? "", "district": recipient?.district ?? "", "relation": recipient?.relation ?? "", "mobileNumber": recipient?.mobileNumber ?? "", "userId": getUserId(), "reason": recipient?.reason ?? ""] } else { return ["firstName": recipient?.firstName ?? "", "middleName": recipient?.middleName ?? "", "lastName": recipient?.lastName ?? "", "city": recipient?.city ?? "", "state": recipient?.state ?? "", "address": recipient?.address ?? "", "country": recipient?.country ?? "", "district": recipient?.district ?? "", "relation": recipient?.relation ?? "", "mobileNumber": recipient?.mobileNumber ?? "", "userId": getUserId(), "reason": recipient?.reason ?? ""] } } else { if recipient.middleName == nil { return ["firstName": recipient?.firstName ?? "", "lastName": recipient?.lastName ?? "", "city": recipient?.city ?? "", "state": recipient?.state ?? "", "address": recipient?.address ?? "", "country": recipient?.country ?? "", "district": recipient?.district ?? "", "relation": recipient?.relation ?? "", "mobileNumber": recipient?.mobileNumber ?? "", "email": recipient?.email ?? "", "userId": getUserId(), "reason": recipient?.reason ?? ""] } else { return ["firstName": recipient?.firstName ?? "", "middleName": recipient?.middleName ?? "", "lastName": recipient?.lastName ?? "", "city": recipient?.city ?? "", "state": recipient?.state ?? "", "address": recipient?.address ?? "", "country": recipient?.country ?? "", "district": recipient?.district ?? "", "relation": recipient?.relation ?? "", "mobileNumber": recipient?.mobileNumber ?? "", "email": recipient?.email ?? "", "userId": getUserId(), "reason": recipient?.reason ?? ""] } } } /** To remove Recipient - parameter recipientId: id */ func removeRecipient(recipientId: String) { let id = recipientId if !Reachability.isConnectedToNetwork() { self.internetConnection.value = false } else { RestApiMananger.sharedInstance.deleteRecipient(recipientId: recipientId) { result in switch result { case .success(_): self.recipientDeleted.value = true case let .failure(errorJSON): self.setErrorMessage(message: errorJSON["message"].stringValue) self.recipientDeleted.value = false case .updateAccessCode: RestApiMananger.sharedInstance.updateAccessCode(userId: self.userId!, password: self.getLoginPassword()) { result in if result != "Error"{ let uuid = RestApiMananger.sharedInstance.getUUID() UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode") self.removeRecipient(recipientId: id) } } case .logOutUser(): RestApiMananger.sharedInstance.cancelExistingNetworkCalls() self.anotherLogin.value = true case .timeOut: self.recipientDeletedTimeOut.value = false } } } } /** To update recipient details -parameter recipientId: id - parameter updateParams: recipient updated detail info */ func updateRecipient(recipientId: String, updateParams: [String: String]) { let id = recipientId let upd_params = updateParams if !Reachability.isConnectedToNetwork() { self.internetConnection.value = false } else { RestApiMananger.sharedInstance.updateRecipient(recipientId: recipientId, recipientDetails: updateParams) { result in switch result { case .success(_): self.recipientCreatedUpdated.value = true case let .failure(errorJSON): self.setErrorMessage(message: errorJSON["message"].stringValue) self.recipientCreatedUpdated.value = false case .updateAccessCode: RestApiMananger.sharedInstance.updateAccessCode(userId: self.userId!, password: self.getLoginPassword()) { result in if result != "Error"{ let uuid = RestApiMananger.sharedInstance.getUUID() UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode") self.updateRecipient(recipientId: id, updateParams: upd_params) } } case .logOutUser(): RestApiMananger.sharedInstance.cancelExistingNetworkCalls() self.anotherLogin.value = true case .timeOut: self.recipientConnectionTimeOut.value = false } } } } /// To create recipient func createRecipient(){ if !Reachability.isConnectedToNetwork() { self.internetConnection.value = false } else { RestApiMananger.sharedInstance.createNewRecipient(recipientDetails: self.getRecipientDetails()) { result in switch result { case let .success(createdJSON): do { self.newRecipient = try JSONDecoder().decode(Recipient.self, from: createdJSON.rawData()) self.recipientCreatedUpdated.value = true } catch { self.recipientCreatedUpdated.value = false } case let .failure(errorJSON): self.setErrorMessage(message: errorJSON["message"].stringValue) self.recipientCreatedUpdated.value = false case .updateAccessCode: RestApiMananger.sharedInstance.updateAccessCode(userId: self.userId!, password: self.getLoginPassword()) { result in if result != "Error"{ let uuid = RestApiMananger.sharedInstance.getUUID() UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode") self.createRecipient() } } case .logOutUser(): RestApiMananger.sharedInstance.cancelExistingNetworkCalls() self.anotherLogin.value = true case .timeOut: self.recipientConnectionTimeOut.value = false } } } } /** To get recipients list with pagination - parameter size: list size - parameter page: page no */ func getAllRecipientsThroughPagination(size: Int , page: Int) { if !Reachability.isConnectedToNetwork() { self.internetConnection.value = false } else { RestApiMananger.sharedInstance.fetchRecipientListThroughPagination(userId: userId!, page: page, size: size) { result in switch result { case let .success(fetchedJSON): self.recipientArray.removeAll() guard fetchedJSON.count > 0 else { self.recipientListObtained.value = true return } for i in 0 ... (fetchedJSON.count-1) { do { let recipient = try JSONDecoder().decode(Recipient.self, from: fetchedJSON[i].rawData()) self.recipientArray.append(recipient) } catch { } } self.recipientListObtained.value = true case let .failure(errorJSON): self.setErrorMessage(message: errorJSON["message"].stringValue) self.recipientListObtained.value = false case .updateAccessCode(): RestApiMananger.sharedInstance.updateAccessCode(userId: self.userId!, password: self.getLoginPassword()) { result in if result != "Error"{ let uuid = RestApiMananger.sharedInstance.getUUID() UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode") self.getAllRecipientsThroughPagination(size: size , page: page) } } case .logOutUser(): RestApiMananger.sharedInstance.cancelExistingNetworkCalls() self.anotherLogin.value = true case .timeOut: self.recipientConnectionTimeOut.value = false } } } } /// - returns: recipient func getCreatedRecipient() -> Recipient { return newRecipient } /// - returns: recipient list func getRecipientArray() -> [Recipient] { return recipientArray } /// - returns: state list func getStateList() -> [String] { return cddStateList } /// - returns: list of state id func getStateValueList() -> [String] { return cddStateValueList } /** To get a state - parameter index: position of state in an array - returns: state */ func getState(index: Int) -> String { return cddStateList[index] } /** To get a state id - parameter index: position of state id in an array - returns: state id */ func getStateValue(index: Int) -> String { let isIndexValid = cddStateValueList.indices.contains(index) if isIndexValid == true { return cddStateValueList[index] } return "" } /// - returns: list of district func getDistrictList() -> [String] { return cddDistrictList } /// - returns: list of district id func getDistrictValueList() -> [String] { return cddDistrictValueList } /** To get a district - parameter index: position of district in an array - returns: district */ func getDistrict(index: Int) -> String { return cddDistrictList[index] } /** To get a district id - parameter index: position of district in an array - returns: district id */ func getDistrictValue(index: Int) -> String { let isIndexValid = cddDistrictValueList.indices.contains(index) if isIndexValid == true { return cddDistrictValueList[index] } return "" } /// - returns: list of transfer reason func getTransferReason() -> [String] { return cddTransferReasonList } /// - returns: list of transfer reason id func getTransferReasonValueList() -> [String] { return cddTransferReasonValueList } /** To get a transferReason id - parameter index: position of transferReason id in an array - returns: transferReason id */ func getTransferReasonValue(index:Int) -> String { let isIndexValid = cddTransferReasonValueList.indices.contains(index) if isIndexValid == true { return cddTransferReasonValueList[index] } return "" } /** To get a transferReason - parameter index: position of transferReason in an array - returns: transferReason */ func getTransferReasonName(index: Int) -> String { return cddTransferReasonList[index] } /// - returns: list of relation func getRelationList() -> [String] { return cddRelationList } /// - returns: list of relation id func getRelationValueList() -> [String] { return cddRelationValueList } /** To get a relation id - parameter index: position of relation id in an array - returns: relation id */ func getRelationValue(index: Int) -> String{ let isIndexValid = cddRelationValueList.indices.contains(index) if isIndexValid == true { return cddRelationValueList[index] } return "" } /** To get a relation - parameter index: position of relation in an array - returns: relation */ func getRelationName(index: Int) -> String { return cddRelationList[index] } /// - returns: list of country detail func getCountryList() -> [AgentCountryList] { return countryList } /** To get a Country Flag Url - parameter index: position of Country Flag Url in an array - returns: Country Flag Url */ func getCountryFlagUrl(index: Int) -> String { if let countryFlag = countryList[index].flagUrl { return countryFlag } return "" } /** To get a Country id - parameter index: position of Country id in an array - returns: Country id */ func getCountryId(index: Int) -> String { let isIndexValid = countryList.indices.contains(index) if isIndexValid == true{ if let countryId = countryList[index].countryId{ return countryId } } return "" } /** To get a Country name - parameter index: position of Country name in an array - returns: Country name */ func getCountryName(index: Int) -> String { return countryList[index].country! } /// - returns: list of Country name func getCountryNameList() -> [String]{ return countryList.map{$0.country!} } /// - returns: list of country id func getCountryIdList() -> [String]{ return countryList.map{$0.countryId!} } /// - returns: list of country flag url func getCountryFlagUrlList() -> [String]{ return countryList.map{$0.flagUrl ?? ""} } /** To set a Country id - parameter referenceIndex: position of Country id in an array */ func setCountryId(referenceIndex: Int) { recipient.country = cddCountryIdList[referenceIndex] } /** To set a transfer reason - parameter referenceIndex: position of transfer reason in an array */ func setTransferReason(referenceIndex: Int) { recipient.reason = cddTransferReasonValueList[referenceIndex] } /** To set a Relation - parameter referenceIndex: position of Relation in an array */ func setRelation(referenceIndex: Int) { recipient.relation = cddRelationValueList[referenceIndex] } /** To set a state - parameter referenceIndex: position of state in an array */ func setState(referenceIndex: Int) { let isIndexValid = cddStateValueList.indices.contains(referenceIndex) if isIndexValid == true{ recipient.state = cddStateValueList[referenceIndex] } } /** To set a District - parameter referenceIndex: position of District in an array */ func setDistrict(referenceIndex: Int) { recipient.district = cddDistrictValueList[referenceIndex] } /** To get cdd list such as occupation , relation, state ect - parameter cddName: cddcode - parameter param: cdd info */ func fetchCDDListFor(cddName: String, param: [String: String]) { if !Reachability.isConnectedToNetwork() { self.internetConnection.value = false } else { RestApiMananger.sharedInstance.getCDDListFor(cddCode: cddName, param: param) { result in switch result { case let .success(cddJSON): switch cddName { case cddCode.TransferReason.rawValue: self.cddTransferReasonList.removeAll() self.cddTransferReasonValueList.removeAll() case cddCode.Province.rawValue: self.cddStateValueList.removeAll() self.cddStateList.removeAll() case cddCode.District.rawValue: self.cddDistrictList.removeAll() self.cddDistrictValueList.removeAll() case cddCode.Relation.rawValue: self.cddRelationList.removeAll() self.cddRelationValueList.removeAll() default: return } if cddJSON.count > 0 { for i in 0 ... (cddJSON.count-1) { do { let cddNameValuePair = try JSONDecoder().decode(Cdd.self, from: cddJSON[i].rawData()) switch cddName { /// used for transfer reason case cddCode.TransferReason.rawValue: self.cddTransferReasonList.append(cddNameValuePair.name) self.cddTransferReasonValueList.append(cddNameValuePair.value) case cddCode.Province.rawValue: self.cddStateList.append(cddNameValuePair.name) self.cddStateValueList.append(cddNameValuePair.value) case cddCode.District.rawValue: self.cddDistrictList.append(cddNameValuePair.name) self.cddDistrictValueList.append(cddNameValuePair.value) case cddCode.Relation.rawValue: self.cddRelationList.append(cddNameValuePair.name) self.cddRelationValueList.append(cddNameValuePair.value) default: return } } catch { break } } } switch cddName { case cddCode.TransferReason.rawValue: self.cddListAvailable.value = 1 case cddCode.Province.rawValue: self.cddListAvailable.value = 2 case cddCode.District.rawValue: self.cddListAvailable.value = 3 case cddCode.Relation.rawValue: self.cddListAvailable.value = 4 default: return } case let .failure(errorJSON): self.setErrorMessage(message: errorJSON["message"].stringValue) self.cddListAvailable.value = 0 case .updateAccessCode: RestApiMananger.sharedInstance.updateAccessCode(userId: self.userId!, password: self.getLoginPassword()) { result in if result != "Error"{ let uuid = RestApiMananger.sharedInstance.getUUID() UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode") self.fetchCDDListFor(cddName: cddName, param: param) } } case .logOutUser(): RestApiMananger.sharedInstance.cancelExistingNetworkCalls() self.anotherLogin.value = true case .timeOut: self.recipientConnectionTimeOut.value = false } } } } /// To get list of country func fetchListOfCountry(){ if !Reachability.isConnectedToNetwork() { self.internetConnection.value = false } else { RestApiMananger.sharedInstance.fetchCountryList() { result in switch result { case let .success(countryListJSON): self.countryList.removeAll() guard countryListJSON.count > 0 else { self.cddCountryListAvailable.value = true return } for i in 0 ... (countryListJSON.count-1) { do { let cddCountry = try JSONDecoder().decode(AgentCountryList.self, from: countryListJSON[i].rawData()) if cddCountry.countryId != "118" { self.countryList.append(cddCountry) self.cddCountryList.append(cddCountry.country!) if let flagUrl = cddCountry.flagUrl { self.cddCountryFlag.append(flagUrl) } else { self.cddCountryFlag.append("") } self.cddCountryIdList.append(cddCountry.countryId!) } } catch { self.cddCountryListAvailable.value = false } } self.cddCountryListAvailable.value = true case let .failure(errorJSON): self.setErrorMessage(message: errorJSON["message"].stringValue) case .updateAccessCode: RestApiMananger.sharedInstance.updateAccessCode(userId: self.userId!, password: self.getLoginPassword()) { result in if result != "Error"{ let uuid = RestApiMananger.sharedInstance.getUUID() UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode") self.fetchListOfCountry() } } case .logOutUser(): RestApiMananger.sharedInstance.cancelExistingNetworkCalls() self.anotherLogin.value = true case .timeOut: self.recipientConnectionTimeOut.value = false } } } } /** To get inex of a country id - parameter id: position of country id in an array - returns: index */ func getIndex(id: String) -> Int { return getCountryIdList().index(of: id)! } /** check empty textfield in array - parameter arrayofInfo: list of textfield - returns: Bool */ func allFieldsFilled(arrayofInfo: [String]) -> Bool { for info in arrayofInfo { if info.isBlank { return false } } return true } }