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

6 years ago
  1. //
  2. // MobileRechargeViewModel.swift
  3. // GMERemittance
  4. //
  5. // Created by Sujal on 1/14/18.
  6. // Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved.
  7. //
  8. import Foundation
  9. class MobileRechargeViewModel: ModelExtension {
  10. let user_id = UserDefaults.standard.object(forKey: "com.gmeremit.username") as? String
  11. private var mobileNumber: String!
  12. private var countryCode: String!
  13. private var networkOperator: String!
  14. private var topUpAmount: String = String("0")
  15. private var country: String!
  16. private var countryId: String!
  17. private var telecomId: String!
  18. private var transactionNumber: String!
  19. private var rechargeResponseDetails: [String: String]?
  20. private var topUpAmountNepal: [String]!
  21. private var topUpAmountKorea: [String]!
  22. private var mobileOperatorArray = [MobileOperator]()
  23. private var rechargeAmountObject: AvailableRechargeAmounts?
  24. var isValidNumber: Box<Bool?> = Box(nil)
  25. var mobileToppedUp: Box<Bool?> = Box(nil)
  26. var mobileOperatorBool: Box<Bool?> = Box(nil)
  27. var mobileRechargeListBool: Box<Bool?> = Box(nil)
  28. var invalidDeviceMessage: String = "nil"
  29. var rechargeConnectionTimeOut: Box<Bool?> = Box(nil)
  30. /**
  31. Check mobile is valid or not
  32. - Parameter enteredNumber: mobile number
  33. */
  34. func updateMobileNumber(enteredNumber: String) {
  35. mobileNumber = enteredNumber
  36. print("number \(enteredNumber)")
  37. //checkMobileNumber(number: mobileNumber)
  38. }
  39. /**
  40. Invalid error message
  41. - Parameter error: json error message
  42. */
  43. func setInvalidDeviceMessageError(error: String){
  44. self.invalidDeviceMessage = error
  45. }
  46. /**
  47. - returns : invalid device error messsage
  48. */
  49. func getInvalideDeviceMessageError() -> String{
  50. if self.invalidDeviceMessage != "nil"{
  51. return invalidDeviceMessage
  52. }
  53. return "Unknown error."
  54. }
  55. /**
  56. - returns: mobile number
  57. */
  58. func getMobileNumber() -> String {
  59. return mobileNumber
  60. }
  61. /**
  62. - returns : transaction number
  63. */
  64. func getTransactionNumber() -> String {
  65. return transactionNumber
  66. }
  67. /**
  68. Set country code
  69. - Parameter countryCode: country provided with unique code
  70. */
  71. func setCountryCode(countryCode: String) {
  72. self.countryCode = countryCode
  73. }
  74. /**
  75. Get country code
  76. - returns: country code
  77. */
  78. func getCountryCode() -> String {
  79. return countryCode
  80. }
  81. /**
  82. - returns: network operator
  83. */
  84. func getNetworkOperator() -> String {
  85. return networkOperator
  86. }
  87. /**
  88. - returns: topUp amount
  89. */
  90. func getTopUpAmount() -> String {
  91. return topUpAmount
  92. }
  93. /**
  94. Set top up amount
  95. - Parameter topUpAmount: set topUp amount
  96. */
  97. func setTopUpAmount(topUpAmount: String) {
  98. self.topUpAmount = topUpAmount
  99. }
  100. /**
  101. Get recharge response details
  102. - returns: recharge response details
  103. */
  104. func getRechargeResponseDetails() -> [String: String] {
  105. if let responseDetails = rechargeResponseDetails{
  106. return responseDetails
  107. }else{
  108. return ["N/A":"N/A"]
  109. }
  110. }
  111. /**
  112. Check mobile number
  113. - Parameter number: mobile number
  114. */
  115. func checkMobileNumber(number: String) {
  116. print("number \(number)")
  117. guard number.count == 10 else {
  118. print("number false \(number)")
  119. print("number false \(number.count)")
  120. isValidNumber.value = false
  121. return
  122. }
  123. print("number else \(number)")
  124. isValidNumber.value = true
  125. }
  126. /**
  127. TODO -> Check this function is used or not.
  128. */
  129. func getTopUpAmountforNepal() -> [String]{
  130. if topUpAmountNepal == nil {
  131. topUpAmountNepal = ["100", "200", "500"]
  132. }
  133. return topUpAmountNepal!
  134. }
  135. /**
  136. TODO -> Check this function is used or not.
  137. */
  138. func getTopUpAmountforKorea() -> [String]{
  139. if topUpAmountKorea == nil {
  140. topUpAmountKorea = ["100", "200", "300", "500", "700"]
  141. }
  142. return topUpAmountKorea!
  143. }
  144. /**
  145. Get telecom operator
  146. - Parameter isNativeCountry: boolean to check native country
  147. - Parameter mobileNumber: mobile number
  148. - returns: integer to check type of operator
  149. */
  150. func getTelecomOperator(isNativeCountry: Bool, mobileNumber: String) -> Int {
  151. if isNativeCountry {
  152. country = "Nepal"
  153. countryId = "151"
  154. switch mobileNumber.prefix(4) {
  155. case "9841":
  156. networkOperator = "NTC"
  157. return 1
  158. case "9803":
  159. networkOperator = "NCell"
  160. return 2
  161. default:
  162. networkOperator = "Unidentified"
  163. return 0
  164. }
  165. } else {
  166. country = "Korea"
  167. countryId = "118"
  168. networkOperator = "KoreanTelecom"
  169. return 1
  170. }
  171. }
  172. /**
  173. - returns: array of mobile operator
  174. */
  175. func getMobileOperator() -> [MobileOperator] {
  176. return self.mobileOperatorArray
  177. }
  178. /**
  179. - returns: array of recharge amounts
  180. */
  181. func getRechargeAmounts() -> AvailableRechargeAmounts? {
  182. if let object = self.rechargeAmountObject{
  183. return object
  184. }
  185. return nil
  186. }
  187. /**
  188. - Set telecom id
  189. - Parameter telecomeId: telecom id
  190. */
  191. func setTelecomId(telecomId: String){
  192. self.telecomId = telecomId
  193. }
  194. /**
  195. Recharge request
  196. - Parameter password: password of user
  197. - Parameter transferAmount: amount selected by user to transfer
  198. */
  199. func topUpMobile(password: String,transferAmount: String) {
  200. let params: [String: String] = ["userId": getUserId(),
  201. "amount": transferAmount,
  202. "mobileNumber": mobileNumber,
  203. "country": countryId,
  204. "telecomId": telecomId,
  205. "txnPassword": password]
  206. if !Reachability.isConnectedToNetwork() {
  207. self.internetConnection.value = false
  208. } else {
  209. RestApiMananger.sharedInstance.rechargeMobile(rechargeDetails: params) { result in
  210. switch result {
  211. case let .success(rechargedJSON):
  212. self.rechargeResponseDetails = ["receiverPhone": rechargedJSON["receiverPhone"].stringValue,
  213. "date": rechargedJSON["date"].stringValue,
  214. "amount": rechargedJSON["amount"].stringValue]
  215. self.transactionNumber = rechargedJSON["transactionId"].stringValue
  216. self.mobileToppedUp.value = true
  217. case let .failure(errorJSON):
  218. self.setErrorMessage(message: errorJSON["message"].stringValue)
  219. self.mobileToppedUp.value = false
  220. case .updateAccessCode:
  221. RestApiMananger.sharedInstance.updateAccessCode(userId: self.user_id!, password: self.getLoginPassword()) {
  222. result in
  223. if result != "Error"{
  224. let uuid = RestApiMananger.sharedInstance.getUUID()
  225. UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode")
  226. self.topUpMobile(password: password, transferAmount: transferAmount)
  227. }
  228. }
  229. case .logOutUser():
  230. RestApiMananger.sharedInstance.cancelExistingNetworkCalls()
  231. self.anotherLogin.value = true
  232. case .timeOut:
  233. self.rechargeConnectionTimeOut.value = false
  234. }
  235. }
  236. }
  237. }
  238. /**
  239. Request for mobile operator
  240. */
  241. func callMobileOperatorApi(){
  242. let params: [String: String] = ["countryID": "151"]
  243. if !Reachability.isConnectedToNetwork() {
  244. self.internetConnection.value = false
  245. }
  246. else{
  247. RestApiMananger.sharedInstance.callMobileOperator(rechargeDetails: params) { result in
  248. switch result {
  249. case let .success(rechargedJSON):
  250. if rechargedJSON.count > 0 {
  251. for i in 0 ... (rechargedJSON.count-1) {
  252. do{
  253. let mobileOperator = try JSONDecoder().decode(MobileOperator.self, from: rechargedJSON[i].rawData())
  254. self.mobileOperatorArray.append(mobileOperator)
  255. }
  256. catch {
  257. }
  258. }
  259. }
  260. self.mobileOperatorBool.value = true
  261. self.mobileToppedUp.value = true
  262. case let .failure(errorJSON):
  263. self.setErrorMessage(message: errorJSON["message"].stringValue)
  264. self.mobileOperatorBool.value = false
  265. case .updateAccessCode:
  266. RestApiMananger.sharedInstance.updateAccessCode(userId: self.user_id!, password: self.getLoginPassword()) {
  267. result in
  268. if result != "Error"{
  269. let uuid = RestApiMananger.sharedInstance.getUUID()
  270. UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode")
  271. self.callMobileOperatorApi()
  272. }
  273. } case .logOutUser():
  274. RestApiMananger.sharedInstance.cancelExistingNetworkCalls()
  275. self.anotherLogin.value = true
  276. case .timeOut:
  277. self.rechargeConnectionTimeOut.value = false
  278. }
  279. }
  280. }
  281. }
  282. /**
  283. Recharge Amount request
  284. - Parameter telecomId: id that represent telecom type like NTC,NCELL
  285. - Parameter mobileNumber: mobile number
  286. */
  287. func callApiForListofRechargeAmounts(telecomId: String,mobileNumber: String) {
  288. let params: [String: String] = ["telecomId": telecomId,
  289. "mobileNumber": mobileNumber]
  290. if !Reachability.isConnectedToNetwork() {
  291. self.internetConnection.value = false
  292. } else {
  293. RestApiMananger.sharedInstance.amountsForMobileRecharge(rechargeDetails: params) { result in
  294. switch result {
  295. case let .success(rechargedJSON):
  296. if rechargedJSON.count > 0 {
  297. do{
  298. let rechargeAmounts = try JSONDecoder().decode(AvailableRechargeAmounts.self, from: rechargedJSON.rawData())
  299. self.rechargeAmountObject = rechargeAmounts
  300. }catch let error{
  301. print("Exception Error \(error)")
  302. }
  303. }
  304. self.mobileRechargeListBool.value = true
  305. case let .failure(errorJSON):
  306. self.setErrorMessage(message: errorJSON["message"].stringValue)
  307. self.setInvalidDeviceMessageError(error: errorJSON["message"].stringValue)
  308. self.mobileRechargeListBool.value = false
  309. case .updateAccessCode:
  310. RestApiMananger.sharedInstance.updateAccessCode(userId: self.user_id!, password: self.getLoginPassword()) {
  311. result in
  312. if result != "Error"{
  313. let uuid = RestApiMananger.sharedInstance.getUUID()
  314. UserDefaults.standard.set((result + ":" + uuid).toBase64(), forKey: "com.gmeremit.accessCode")
  315. self.callApiForListofRechargeAmounts(telecomId: telecomId,mobileNumber: mobileNumber)
  316. }
  317. }
  318. case .logOutUser():
  319. RestApiMananger.sharedInstance.cancelExistingNetworkCalls()
  320. self.anotherLogin.value = true
  321. case .timeOut:
  322. self.rechargeConnectionTimeOut.value = false
  323. }
  324. }
  325. }
  326. }
  327. }