You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

377 lines
13 KiB

//
// MobileRechargeViewModel.swift
// GMERemittance
//
// Created by Sujal on 1/14/18.
// Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved.
//
import Foundation
class MobileRechargeViewModel: ModelExtension {
let user_id = UserDefaults.standard.object(forKey: "com.gmeremit.username") as? String
private var mobileNumber: String!
private var countryCode: String!
private var networkOperator: String!
private var topUpAmount: String = String("0")
private var country: String!
private var countryId: String!
private var telecomId: String!
private var transactionNumber: String!
private var rechargeResponseDetails: [String: String]?
private var topUpAmountNepal: [String]!
private var topUpAmountKorea: [String]!
private var mobileOperatorArray = [MobileOperator]()
private var rechargeAmountObject: AvailableRechargeAmounts?
var isValidNumber: Box<Bool?> = Box(nil)
var mobileToppedUp: Box<Bool?> = Box(nil)
var mobileOperatorBool: Box<Bool?> = Box(nil)
var mobileRechargeListBool: Box<Bool?> = Box(nil)
var invalidDeviceMessage: String = "nil"
var rechargeConnectionTimeOut: Box<Bool?> = Box(nil)
/**
Check mobile is valid or not
- Parameter enteredNumber: mobile number
*/
func updateMobileNumber(enteredNumber: String) {
mobileNumber = enteredNumber
print("number \(enteredNumber)")
//checkMobileNumber(number: mobileNumber)
}
/**
Invalid error message
- Parameter error: json error message
*/
func setInvalidDeviceMessageError(error: String){
self.invalidDeviceMessage = error
}
/**
- returns : invalid device error messsage
*/
func getInvalideDeviceMessageError() -> String{
if self.invalidDeviceMessage != "nil"{
return invalidDeviceMessage
}
return "Unknown error."
}
/**
- returns: mobile number
*/
func getMobileNumber() -> String {
return mobileNumber
}
/**
- returns : transaction number
*/
func getTransactionNumber() -> String {
return transactionNumber
}
/**
Set country code
- Parameter countryCode: country provided with unique code
*/
func setCountryCode(countryCode: String) {
self.countryCode = countryCode
}
/**
Get country code
- returns: country code
*/
func getCountryCode() -> String {
return countryCode
}
/**
- returns: network operator
*/
func getNetworkOperator() -> String {
return networkOperator
}
/**
- returns: topUp amount
*/
func getTopUpAmount() -> String {
return topUpAmount
}
/**
Set top up amount
- Parameter topUpAmount: set topUp amount
*/
func setTopUpAmount(topUpAmount: String) {
self.topUpAmount = topUpAmount
}
/**
Get recharge response details
- returns: recharge response details
*/
func getRechargeResponseDetails() -> [String: String] {
if let responseDetails = rechargeResponseDetails{
return responseDetails
}else{
return ["N/A":"N/A"]
}
}
/**
Check mobile number
- Parameter number: mobile number
*/
func checkMobileNumber(number: String) {
print("number \(number)")
guard number.count == 10 else {
print("number false \(number)")
print("number false \(number.count)")
isValidNumber.value = false
return
}
print("number else \(number)")
isValidNumber.value = true
}
/**
TODO -> Check this function is used or not.
*/
func getTopUpAmountforNepal() -> [String]{
if topUpAmountNepal == nil {
topUpAmountNepal = ["100", "200", "500"]
}
return topUpAmountNepal!
}
/**
TODO -> Check this function is used or not.
*/
func getTopUpAmountforKorea() -> [String]{
if topUpAmountKorea == nil {
topUpAmountKorea = ["100", "200", "300", "500", "700"]
}
return topUpAmountKorea!
}
/**
Get telecom operator
- Parameter isNativeCountry: boolean to check native country
- Parameter mobileNumber: mobile number
- returns: integer to check type of operator
*/
func getTelecomOperator(isNativeCountry: Bool, mobileNumber: String) -> Int {
if isNativeCountry {
country = "Nepal"
countryId = "151"
switch mobileNumber.prefix(4) {
case "9841":
networkOperator = "NTC"
return 1
case "9803":
networkOperator = "NCell"
return 2
default:
networkOperator = "Unidentified"
return 0
}
} else {
country = "Korea"
countryId = "118"
networkOperator = "KoreanTelecom"
return 1
}
}
/**
- returns: array of mobile operator
*/
func getMobileOperator() -> [MobileOperator] {
return self.mobileOperatorArray
}
/**
- returns: array of recharge amounts
*/
func getRechargeAmounts() -> AvailableRechargeAmounts? {
if let object = self.rechargeAmountObject{
return object
}
return nil
}
/**
- Set telecom id
- Parameter telecomeId: telecom id
*/
func setTelecomId(telecomId: String){
self.telecomId = telecomId
}
/**
Recharge request
- Parameter password: password of user
- Parameter transferAmount: amount selected by user to transfer
*/
func topUpMobile(password: String,transferAmount: String) {
let params: [String: String] = ["userId": getUserId(),
"amount": transferAmount,
"mobileNumber": mobileNumber,
"country": countryId,
"telecomId": telecomId,
"txnPassword": password]
if !Reachability.isConnectedToNetwork() {
self.internetConnection.value = false
} else {
RestApiMananger.sharedInstance.rechargeMobile(rechargeDetails: params) { result in
switch result {
case let .success(rechargedJSON):
self.rechargeResponseDetails = ["receiverPhone": rechargedJSON["receiverPhone"].stringValue,
"date": rechargedJSON["date"].stringValue,
"amount": rechargedJSON["amount"].stringValue]
self.transactionNumber = rechargedJSON["transactionId"].stringValue
self.mobileToppedUp.value = true
case let .failure(errorJSON):
self.setErrorMessage(message: errorJSON["message"].stringValue)
self.mobileToppedUp.value = false
case .updateAccessCode:
RestApiMananger.sharedInstance.updateAccessCode(userId: self.user_id!, password: self.getLoginPassword()) {
result in
if result != "Error"{
let uuid = RestApiMananger.sharedInstance.getUUID()
UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode")
self.topUpMobile(password: password, transferAmount: transferAmount)
}
}
case .logOutUser():
RestApiMananger.sharedInstance.cancelExistingNetworkCalls()
self.anotherLogin.value = true
case .timeOut:
self.rechargeConnectionTimeOut.value = false
}
}
}
}
/**
Request for mobile operator
*/
func callMobileOperatorApi(){
let params: [String: String] = ["countryID": "151"]
if !Reachability.isConnectedToNetwork() {
self.internetConnection.value = false
}
else{
RestApiMananger.sharedInstance.callMobileOperator(rechargeDetails: params) { result in
switch result {
case let .success(rechargedJSON):
if rechargedJSON.count > 0 {
for i in 0 ... (rechargedJSON.count-1) {
do{
let mobileOperator = try JSONDecoder().decode(MobileOperator.self, from: rechargedJSON[i].rawData())
self.mobileOperatorArray.append(mobileOperator)
}
catch {
}
}
}
self.mobileOperatorBool.value = true
self.mobileToppedUp.value = true
case let .failure(errorJSON):
self.setErrorMessage(message: errorJSON["message"].stringValue)
self.mobileOperatorBool.value = false
case .updateAccessCode:
RestApiMananger.sharedInstance.updateAccessCode(userId: self.user_id!, password: self.getLoginPassword()) {
result in
if result != "Error"{
let uuid = RestApiMananger.sharedInstance.getUUID()
UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode")
self.callMobileOperatorApi()
}
} case .logOutUser():
RestApiMananger.sharedInstance.cancelExistingNetworkCalls()
self.anotherLogin.value = true
case .timeOut:
self.rechargeConnectionTimeOut.value = false
}
}
}
}
/**
Recharge Amount request
- Parameter telecomId: id that represent telecom type like NTC,NCELL
- Parameter mobileNumber: mobile number
*/
func callApiForListofRechargeAmounts(telecomId: String,mobileNumber: String) {
let params: [String: String] = ["telecomId": telecomId,
"mobileNumber": mobileNumber]
if !Reachability.isConnectedToNetwork() {
self.internetConnection.value = false
} else {
RestApiMananger.sharedInstance.amountsForMobileRecharge(rechargeDetails: params) { result in
switch result {
case let .success(rechargedJSON):
if rechargedJSON.count > 0 {
do{
let rechargeAmounts = try JSONDecoder().decode(AvailableRechargeAmounts.self, from: rechargedJSON.rawData())
self.rechargeAmountObject = rechargeAmounts
}catch let error{
print("Exception Error \(error)")
}
}
self.mobileRechargeListBool.value = true
case let .failure(errorJSON):
self.setErrorMessage(message: errorJSON["message"].stringValue)
self.setInvalidDeviceMessageError(error: errorJSON["message"].stringValue)
self.mobileRechargeListBool.value = false
case .updateAccessCode:
RestApiMananger.sharedInstance.updateAccessCode(userId: self.user_id!, password: self.getLoginPassword()) {
result in
if result != "Error"{
let uuid = RestApiMananger.sharedInstance.getUUID()
UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode")
self.callApiForListofRechargeAmounts(telecomId: telecomId,mobileNumber: mobileNumber)
}
}
case .logOutUser():
RestApiMananger.sharedInstance.cancelExistingNetworkCalls()
self.anotherLogin.value = true
case .timeOut:
self.rechargeConnectionTimeOut.value = false
}
}
}
}
}