// // SplashScreenViewModel.swift // Learn Genie // // Created by Suraj Kumar Mandal on 01/09/21. // import Foundation import Alamofire import SSZipArchive import RealmSwift class SplashScreenViewModel { var delegate : SplashScreenViewProtocol? func generateCookie() { if let delegate = delegate { let url = ApiUrl.BASE_URL + ApiUrl.API_AUTH let params: [String:Any]? params = [ "username" : "admin", "password" : "mahindrapass123" ] print(params!) AF.request(url, method: HTTPMethod.post, parameters: params).responseData { (responseObject) -> Void in if let responseStatus = responseObject.response?.statusCode { if responseStatus != 200 { // error print("error...") } else { // view all cookies print(HTTPCookieStorage.shared.cookies!) for cookie in HTTPCookieStorage.shared.cookies! { print(cookie.value) UserDefaultsConstant.setValueInUserDefaults(objValue: cookie.value, for: "cookieValue") //self.getRole() //delegate.groupLeave() delegate.callDataAPI() } } } } } } func getRole() { if let delegate = delegate { DBManager.sharedInstance.deleteAllDatabase() let url = "\(ApiUrl.BASE_URL + ApiUrl.API_ROLE).json" let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" let headers: HTTPHeaders = [ "Content-Type": "application/json", "Accept": "application/json", "Cookie": "\(Constant.CookieName) = \(cookieValue)" ] print(headers) AF.request(url, method: HTTPMethod.post, encoding: JSONEncoding.default, headers: headers).responseJSON { response in switch response.result { case .success(let value): let roleData = value as! [NSDictionary] for item in roleData { let id = item.value(forKey: "id") as! NSNumber; let name = item.value(forKey: "name") as? String ?? ""; let authority = item.value(forKey: "authority") as? String ?? ""; var roleModel = [RoleModel]() let newRoleModel = RoleModel(id: Int(truncating: id), name: name, authority: authority) roleModel.append(newRoleModel) DBManager.sharedInstance.addData(objs: roleModel) } let realmEntries = DBManager.sharedInstance.database.objects(RoleModel.self) print("role count") print(realmEntries.count) print(roleData.count) // if both counts doesn't match let db_count = realmEntries.count - roleData.count if db_count > 0 { let array = Array(1...db_count) for value in array { var roleModel = [RoleModel]() let data = DBManager.sharedInstance.getObjects(type: RoleModel.self)? [realmEntries.count - value] as! RoleModel roleModel.append(data) DBManager.sharedInstance.deleteFromDb(object: roleModel) } } //self.getLanguage() delegate.groupLeave() case .failure(let error): print(error) } } } } func getLanguage() { if let delegate = delegate { let url = "\(ApiUrl.BASE_URL + ApiUrl.API_LANGUAGE).json" let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" let headers: HTTPHeaders = [ "Content-Type": "application/json", "Accept": "application/json", "Cookie": "\(Constant.CookieName) = \(cookieValue)" ] print(headers) AF.request(url, method: HTTPMethod.post, encoding: JSONEncoding.default, headers: headers).responseJSON { response in switch response.result { case .success(let value): let languageArray = value as! [NSDictionary] for item in languageArray { let id = item.value(forKey: "id") as! NSNumber; let shortName = item.value(forKey: "shortName") as? String ?? "" ; let dateCreated = item.value(forKey: "dateCreated") as? String ?? "" ; let lastUpdated = item.value(forKey: "lastUpdated") as? String ?? "" ; let name = item.value(forKey: "name") as? String ?? "" ; var languageModel = [LanguageModel]() let newLanguageModel = LanguageModel(id: Int(truncating: id), shortName: shortName, dateCreated: dateCreated, lastUpdated: lastUpdated, name: name) languageModel.append(newLanguageModel) DBManager.sharedInstance.addData(objs: languageModel) } let realmEntries = DBManager.sharedInstance.database.objects(LanguageModel.self) print("language count") print(realmEntries.count) print(languageArray.count) // if both counts doesn't match let db_count = realmEntries.count - languageArray.count if db_count > 0 { let array = Array(1...db_count) for value in array { var languageModel = [LanguageModel]() let data = DBManager.sharedInstance.getObjects(type: LanguageModel.self)? [realmEntries.count - value] as! LanguageModel languageModel.append(data) DBManager.sharedInstance.deleteFromDb(object: languageModel) } } //self.getTranslation(offset: 0) delegate.groupLeave() case .failure(let error): print(error) } } } } func getTranslation(offset:Int) { if let delegate = delegate { let max = 10 let url = "\(ApiUrl.BASE_URL + ApiUrl.API_TRANSLATION).json?max=\(max)&offset=\(offset)" let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" let headers: HTTPHeaders = [ "Content-Type": "application/json", "Accept": "application/json", "Cookie": "\(Constant.CookieName) = \(cookieValue)" ] print(headers) //let params: [String:Any]? let params = [ "max" : max, "offset" : offset ] print(params) AF.request(url, method: .get, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in switch response.result { case .success(let value): let translationArray = value as! [NSDictionary] if translationArray != [] { print(translationArray) for item in translationArray { let id = item.value(forKey: "id") as! NSNumber; let originalText = item.value(forKey: "originalText") as? String ?? "" ; let language = item.value(forKey: "language") as? NSObject; let languageId = language?.value(forKey: "id") as! NSNumber; let translatedText = item.value(forKey: "translatedText") as? String ?? "" ; var translationModel = [TranslationModel]() let newtranslationModel = TranslationModel(id: Int(truncating: id), originalText: originalText, languageId: Int(truncating: languageId), translatedText: translatedText) translationModel.append(newtranslationModel) DBManager.sharedInstance.addData(objs: translationModel) } let realmEntries = DBManager.sharedInstance.database.objects(TranslationModel.self) print("translation count") print(realmEntries.count) self.getTranslation(offset: offset + max) } else { //Next API call //self.getState(offset: 0) delegate.groupLeave() } case .failure(let error): print(error) } } } } func getState(offset:Int) { if let delegate = delegate { let max = 10 let url = "\(ApiUrl.BASE_URL + ApiUrl.API_STATE).json?max=\(max)&offset=\(offset)" let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" let headers: HTTPHeaders = [ "Content-Type": "application/json", "Accept": "application/json", "Cookie": "\(Constant.CookieName) = \(cookieValue)" ] print(headers) print(url) AF.request(url, method: .get, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in switch response.result { case .success(let value): let translationArray = value as! [NSDictionary] if translationArray != [] { print(translationArray) for item in translationArray { let id = item.value(forKey: "id") as! NSNumber; let stateName = item.value(forKey: "stateName") as? String ?? "" ; let stateNameHindi = item.value(forKey: "stateNameHindi") as? String ?? "" ; var stateModel = [StateModel]() let newStateModel = StateModel(id: Int(truncating: id), stateName: stateName, stateNameHindi: stateNameHindi) stateModel.append(newStateModel) DBManager.sharedInstance.addData(objs: stateModel) } let realmEntries = DBManager.sharedInstance.database.objects(StateModel.self) print("state count") print(realmEntries.count) self.getState(offset: offset + max) } else { //Next API call //self.getDistrict(offset: 0) delegate.groupLeave() } case .failure(let error): print(error) } } } } func getDistrict(offset:Int) { if let delegate = delegate { let max = 10 let url = "\(ApiUrl.BASE_URL + ApiUrl.API_DISTRICT).json?max=\(max)&offset=\(offset)" let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" let headers: HTTPHeaders = [ "Content-Type": "application/json", "Accept": "application/json", "Cookie": "\(Constant.CookieName) = \(cookieValue)" ] print(headers) print(url) AF.request(url, method: .get, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in switch response.result { case .success(let value): let translationArray = value as! [NSDictionary] if translationArray != [] { print(translationArray) for item in translationArray { let id = item.value(forKey: "id") as! NSNumber; let districtName = item.value(forKey: "districtName") as? String ?? "" ; let state = item.value(forKey: "state") as? NSObject; let stateId = state?.value(forKey: "id") as! NSNumber; let districtNameHindi = item.value(forKey: "districtNameHindi") as? String ?? "" ; var districtModel = [DistrictModel]() let newDistrictModel = DistrictModel(id: Int(truncating: id), districtName: districtName, stateId: Int(truncating: stateId), districtNameHindi: districtNameHindi) districtModel.append(newDistrictModel) DBManager.sharedInstance.addData(objs: districtModel) } let realmEntries = DBManager.sharedInstance.database.objects(DistrictModel.self) print("district count") print(realmEntries.count) self.getDistrict(offset: offset + max) } else { //Next API call //self.getTopic(offset: 0) delegate.groupLeave() } case .failure(let error): print(error) } } } } func getTopic(offset:Int) { if let delegate = delegate { let max = 10 let url = "\(ApiUrl.BASE_URL + ApiUrl.API_TOPIC).json?max=\(max)&offset=\(offset)" let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" let headers: HTTPHeaders = [ "Content-Type": "application/json", "Accept": "application/json", "Cookie": "\(Constant.CookieName) = \(cookieValue)" ] print(headers) print(url) AF.request(url, method: .get, encoding: URLEncoding.httpBody, headers: headers).responseJSON { response in switch response.result { case .success(let value): let topicArray = value as! [NSDictionary] if topicArray != [] { print(topicArray) for item in topicArray { let id = item.value(forKey: "id") as! NSNumber; let level = item.value(forKey: "level") as? NSObject; let levelId = level?.value(forKey: "id") as! NSNumber; let noOfQuizQuestions = item.value(forKey: "noOfQuizQuestions") as! NSNumber; let video = item.value(forKey: "video") as? String ?? "" ; let dateCreated = item.value(forKey: "dateCreated") as? String ?? "" ; let lastUpdated = item.value(forKey: "lastUpdated") as? String ?? "" ; let name = item.value(forKey: "name") as? String ?? "" ; let questionBank = item.value(forKey: "questionBank") as? NSObject; let questionBankId = questionBank?.value(forKey: "id") as! NSNumber; let content = item.value(forKey: "content") as? String ?? "" ; let language = item.value(forKey: "language") as? NSObject; let languageId = language?.value(forKey: "id") as! NSNumber; var topicModel = [TopicModel]() let newtopicModel = TopicModel(id: Int(truncating: id), levelId: Int(truncating: levelId), noOfQuizQuestions: Int(truncating: noOfQuizQuestions), video: video, dateCreated: dateCreated, lastUpdated: lastUpdated, name: name, questionBankId: Int(truncating: questionBankId), content: content, languageId: Int(truncating: languageId)) topicModel.append(newtopicModel) DBManager.sharedInstance.addData(objs: topicModel) //self.topicDownloader(id: Int(truncating: id)) } let realmEntries = DBManager.sharedInstance.database.objects(TopicModel.self) print("topic count") print(realmEntries.count) self.getTopic(offset: offset + max) } else { //Next API call // delegate.stopActivityIndicator() // delegate.navigation() // print("All api call done!") delegate.groupLeave() } case .failure(let error): print(error) } } } } // func getUserDetails() { // switch UserDefaultsConstant.getValueFromUserDefults(for: Constant.signInMethod) as! String { // case "google": // let url = "\(ApiUrl.BASE_URL + ApiUrl.API_SEARCH_STUDENT)?email=\(emailId)" // print(url) // let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" // let headers: HTTPHeaders = [ // "Content-Type": "application/json", // "Accept": "application/json", // "Cookie": "\(Constant.CookieName) = \(cookieValue)" // ] // print(headers) // // AF.request(url, method: .get, encoding: URLEncoding.httpBody, headers: headers).responseJSON { [self] response in // switch response.result { // case .success(let value): // let data = value as! NSDictionary // print(data) // let id = data.value(forKey: "id") as? Int ?? 0; // if id != 0 { // let userData = value as! NSDictionary // // let accountExpired = userData.value(forKey: "accountExpired") as! NSNumber; // let accountLocked = userData.value(forKey: "accountLocked") as! NSNumber; // let dateCreated = userData.value(forKey: "dateCreated") as? String ?? ""; // let dateOfBirth = userData.value(forKey: "dateOfBirth") as? String ?? ""; // let district = userData.value(forKey: "district") as? NSObject; // let districtId = district?.value(forKey: "id") as! NSNumber; // let email = userData.value(forKey: "email") as? String ?? ""; // let enabled = userData.value(forKey: "enabled") as! NSNumber; // let gender = userData.value(forKey: "gender") as? String ?? ""; // let id = userData.value(forKey: "id") as! NSNumber; // let level = userData.value(forKey: "level") as? NSObject; // let levelId = level?.value(forKey: "id") as! NSNumber; // let mobile = userData.value(forKey: "mobile") as? String ?? ""; // let name = userData.value(forKey: "name") as? String ?? ""; // let password = userData.value(forKey: "password") as? String ?? ""; // let passwordExpired = userData.value(forKey: "passwordExpired") as! NSNumber; // let role = userData.value(forKey: "role") as? NSObject; // let roleId = role?.value(forKey: "id") as! NSNumber; // let state = userData.value(forKey: "state") as? NSObject; // let stateId = state?.value(forKey: "id") as! NSNumber; // let topic = userData.value(forKey: "topic") as? NSObject; // let topicId = topic?.value(forKey: "id") as! NSNumber; // let username = userData.value(forKey: "username") as? String ?? ""; // // var userModel = [UserDetailsModel]() // let newUserModel = UserDetailsModel(accountExpired: Int(truncating: accountExpired), accountLocked: Int(truncating: accountLocked), dateCreated: dateCreated, dateOfBirth: dateOfBirth, districtId: Int(truncating: districtId), email: email, enabled: Int(truncating: enabled), gender: gender, id: Int(truncating: id), levelId: Int(truncating: levelId), mobile: mobile, name: name, password: password, passwordExpired: Int(truncating: passwordExpired), roleId: Int(truncating: roleId), stateId: Int(truncating: stateId), topicId: Int(truncating: topicId), username: username, appleIdentifier: UserDefaults.standard.string(forKey: Constant.userIdentifier) ?? "") // userModel.append(newUserModel) // DBManager.sharedInstance.addData(objs: userModel) // let userModelDB = DBManager.sharedInstance.database.objects(UserDetailsModel.self) // print("user count") // print(userModelDB.count) // // UserDefaultsConstant.setIntValueInUserDefaults(objValue: Int(truncating: id), for: Constant.studentId) // delegate?.groupLeave() // } // case .failure(let error): // print(error) // } // } // case "apple": // let userIdentifier = UserDefaultsConstant.getValueFromUserDefults(for: Constant.userIdentifier) ?? "" // let url = "\(ApiUrl.BASE_URL + ApiUrl.API_SEARCH_APPLE_USERIDENTIFIER)?appleUserIdentifier=\(userIdentifier)" // print(url) // let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? "" // let headers: HTTPHeaders = [ // "Content-Type": "application/json", // "Accept": "application/json", // "Cookie": "\(Constant.CookieName) = \(cookieValue)" // ] // print(headers) // // AF.request(url, method: .get, encoding: URLEncoding.httpBody, headers: headers).responseJSON { [self] response in // switch response.result { // case .success(let value): // let data = value as! NSDictionary // print(data) // let id = data.value(forKey: "id") as? Int ?? 0; // if id != 0 { // let userData = value as! NSDictionary // // let accountExpired = userData.value(forKey: "accountExpired") as! NSNumber; // let accountLocked = userData.value(forKey: "accountLocked") as! NSNumber; // let dateCreated = userData.value(forKey: "dateCreated") as? String ?? ""; // let dateOfBirth = userData.value(forKey: "dateOfBirth") as? String ?? ""; // let district = userData.value(forKey: "district") as? NSObject; // let districtId = district?.value(forKey: "id") as! NSNumber; // let email = userData.value(forKey: "email") as? String ?? ""; // let enabled = userData.value(forKey: "enabled") as! NSNumber; // let gender = userData.value(forKey: "gender") as? String ?? ""; // let id = userData.value(forKey: "id") as! NSNumber; // let level = userData.value(forKey: "level") as? NSObject; // let levelId = level?.value(forKey: "id") as! NSNumber; // let mobile = userData.value(forKey: "mobile") as? String ?? ""; // let name = userData.value(forKey: "name") as? String ?? ""; // let password = userData.value(forKey: "password") as? String ?? ""; // let passwordExpired = userData.value(forKey: "passwordExpired") as! NSNumber; // let role = userData.value(forKey: "role") as? NSObject; // let roleId = role?.value(forKey: "id") as! NSNumber; // let state = userData.value(forKey: "state") as? NSObject; // let stateId = state?.value(forKey: "id") as! NSNumber; // let topic = userData.value(forKey: "topic") as? NSObject; // let topicId = topic?.value(forKey: "id") as! NSNumber; // let username = userData.value(forKey: "username") as? String ?? ""; // let appleUserIdentifier = userData.value(forKey: "appleUserIdentifier") as? String ?? ""; // // var userModel = [UserDetailsModel]() // let newUserModel = UserDetailsModel(accountExpired: Int(truncating: accountExpired), accountLocked: Int(truncating: accountLocked), dateCreated: dateCreated, dateOfBirth: dateOfBirth, districtId: Int(truncating: districtId), email: email, enabled: Int(truncating: enabled), gender: gender, id: Int(truncating: id), levelId: Int(truncating: levelId), mobile: mobile, name: name, password: password, passwordExpired: Int(truncating: passwordExpired), roleId: Int(truncating: roleId), stateId: Int(truncating: stateId), topicId: Int(truncating: topicId), username: username, appleIdentifier: appleUserIdentifier) // userModel.append(newUserModel) // DBManager.sharedInstance.addData(objs: userModel) // let userModelDB = DBManager.sharedInstance.database.objects(UserDetailsModel.self) // print("user count") // print(userModelDB.count) // // UserDefaultsConstant.setIntValueInUserDefaults(objValue: Int(truncating: id), for: Constant.studentId) // //Navigate to Home // DispatchQueue.main.async { // let loaderVC = self.storyboard?.instantiateViewController(withIdentifier:"LoadingAnimationViewController" ) as! LoadingAnimationViewController // self.navigationController?.pushViewController(loaderVC, animated: true) // } // } // case .failure(let error): // print(error) // } // } // default: // <#code#> // } // } } protocol SplashScreenViewProtocol { func callDataAPI() func groupLeave() func stopActivityIndicator() func showToastMessage(message:String) func navigation() }