Bind endBet with API

pull/23/head V4
Emre KARTAL 1 year ago
parent ff9e9f6ed2
commit 1e5e1269e4

@ -0,0 +1,27 @@
//
// BetEndingValidationViewModel.swift
// AllIn
//
// Created by Emre on 07/02/2024.
//
import Foundation
import DependencyInjection
import Model
class BetEndingValidationViewModel: ObservableObject {
var id: String
@Inject var manager: Manager
@Published var selectedAnswer : String?
init(id: String) {
self.id = id
}
func post() {
if let answer = selectedAnswer {
manager.addResponse(withIdBet: id, andResponse: answer)
}
}
}

@ -15,7 +15,9 @@ class BetViewModel: ObservableObject {
@Inject var manager: Manager
@Published private(set) var bets: [Bet] = []
@Published var betsOver: [BetDetail] = []
@Published var showingSheet: Bool = false
init() {
getItems()
}
@ -24,7 +26,12 @@ class BetViewModel: ObservableObject {
manager.getBets(withIndex: 0, withCount: 20) { bets in
self.bets = bets
}
manager.getBetsOver() { bets in
self.betsOver = bets
if !self.betsOver.isEmpty {
self.showingSheet = true
}
print(bets)
}
}
private var cancellables: Set<AnyCancellable> = []
}

@ -10,13 +10,17 @@ import SwiftUI
import Model
import StubLib
struct BetEndingValidation: View {
struct BetEndingValidationView: View {
@Environment(\.dismiss) var dismiss
@State var xOffset: CGFloat = 0
@State var selectedAnswer : String?
var bet: BetDetail = BetStubManager().getABetDetail()
@StateObject private var viewModel: BetEndingValidationViewModel
var bet: BetDetail
init(bet: BetDetail) {
self.bet = bet
self._viewModel = StateObject(wrappedValue: BetEndingValidationViewModel(id: bet.bet.id))
}
var body: some View {
ZStack{
@ -59,12 +63,12 @@ struct BetEndingValidation: View {
.frame(maxWidth: .infinity, alignment: .leading)
VStack(spacing: 14){
ForEach(bet.answers, id: \.self) { answer in
ChoiceFinalAnswerCell(selected : answer.response == selectedAnswer, answer: answer).onTapGesture {
if(selectedAnswer == answer.response){
selectedAnswer = nil
ChoiceFinalAnswerCell(selected : answer.response == viewModel.selectedAnswer, answer: answer).onTapGesture {
if(viewModel.selectedAnswer == answer.response){
viewModel.selectedAnswer = nil
}
else {
selectedAnswer = answer.response
viewModel.selectedAnswer = answer.response
}
}
}
@ -80,8 +84,8 @@ struct BetEndingValidation: View {
.frame(maxWidth: .infinity)
.padding(.vertical, 3)
}
.opacity(selectedAnswer != nil ? 1 : 0)
.animation(.easeInOut(duration: 0.3), value: selectedAnswer != nil)
.opacity(viewModel.selectedAnswer != nil ? 1 : 0)
.animation(.easeInOut(duration: 0.3), value: viewModel.selectedAnswer != nil)
.buttonStyle(.borderedProminent)
.tint(AllInColors.purpleAccentColor)
}

@ -12,7 +12,6 @@ struct BetView: View {
@StateObject private var viewModel = BetViewModel()
@Binding var showMenu: Bool
@State var showingSheet: Bool = false
var body: some View {
@ -28,9 +27,6 @@ struct BetView: View {
ForEach(viewModel.bets, id: \.id) { (bet: Bet) in
BetCard(bet: bet)
}
Button("Show Sheet") {
showingSheet.toggle()
}
}
.padding([.leading,.trailing],25)
@ -57,8 +53,13 @@ struct BetView: View {
.refreshable {
viewModel.getItems()
}
.sheet(isPresented: $showingSheet) {
BetEndingValidation()
.sheet(isPresented: $viewModel.showingSheet, onDismiss: {
viewModel.betsOver.removeFirst()
viewModel.showingSheet = !viewModel.betsOver.isEmpty
}) {
if let firstBetDetail = viewModel.betsOver.first {
BetEndingValidationView(bet: firstBetDetail)
}
}
Spacer()
}

@ -11,6 +11,7 @@ struct DailyGiftPage: View {
enum Step {
case first
case second
case end
}
@ -54,7 +55,7 @@ struct DailyGiftPage: View {
scale = 1.1
}
}
case .end:
case .second:
ZStack {
Image("giftEarnImage")
.rotationEffect(.degrees(Double(rotate) * 10), anchor: .center)
@ -65,7 +66,7 @@ struct DailyGiftPage: View {
}
}
HStack {
Text("+ 123")
Text("+" + gain.description)
.textStyle(weight: .black, color: .white, size: 55)
Image("allcoinWhiteIcon")
.resizable()
@ -87,6 +88,8 @@ struct DailyGiftPage: View {
.onDisappear {
scale2 = 0
}
default :
EmptyView()
}
}
.frame(width: geometry.size.width * 0.8, height: geometry.size.height * 0.4)
@ -94,12 +97,14 @@ struct DailyGiftPage: View {
withAnimation {
switch step {
case .first:
step = .end
step = .second
withAnimation {
AppStateContainer.shared.user?.nbCoins += gain
}
case .end:
case .second:
show = false
step = .end
case .end:
step = .first
}
}

@ -6,7 +6,6 @@ struct DetailsView: View {
@Binding var isModalPresented: Bool
@Binding var isModalParticipated: Bool
@State var progressValue: Float = 0.2
var id: String
@StateObject private var viewModel: DetailsViewModel
var isFinished: Bool {
@ -35,7 +34,6 @@ struct DetailsView: View {
init(isModalPresented: Binding<Bool>, isModalParticipated: Binding<Bool>, id: String) {
self._isModalPresented = isModalPresented
self._isModalParticipated = isModalParticipated
self.id = id
self._viewModel = StateObject(wrappedValue: DetailsViewModel(id: id))
}

@ -63,6 +63,7 @@
EC7A882D2B28D8A1004F226A /* CreationBetView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC7A882C2B28D8A1004F226A /* CreationBetView.swift */; };
EC7A882F2B28E6BE004F226A /* ConfidentialityButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC7A882E2B28E6BE004F226A /* ConfidentialityButton.swift */; };
EC89F7BD2B250D66003821CE /* LoginView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC89F7BC2B250D66003821CE /* LoginView.swift */; };
EC9464E92B7413E1004EEBD8 /* BetEndingValidationViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = EC9464E82B7413E1004EEBD8 /* BetEndingValidationViewModel.swift */; };
ECA9D1C92B2D9ADA0076E0EC /* UserInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECA9D1C82B2D9ADA0076E0EC /* UserInfo.swift */; };
ECA9D1CB2B2DA2320076E0EC /* DropDownFriends.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECA9D1CA2B2DA2320076E0EC /* DropDownFriends.swift */; };
ECB26A132B406A9400FE06B3 /* BetViewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = ECB26A122B406A9400FE06B3 /* BetViewModel.swift */; };
@ -169,6 +170,7 @@
EC7A882C2B28D8A1004F226A /* CreationBetView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreationBetView.swift; sourceTree = "<group>"; };
EC7A882E2B28E6BE004F226A /* ConfidentialityButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfidentialityButton.swift; sourceTree = "<group>"; };
EC89F7BC2B250D66003821CE /* LoginView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginView.swift; sourceTree = "<group>"; };
EC9464E82B7413E1004EEBD8 /* BetEndingValidationViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BetEndingValidationViewModel.swift; sourceTree = "<group>"; };
ECA9D1C82B2D9ADA0076E0EC /* UserInfo.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UserInfo.swift; sourceTree = "<group>"; };
ECA9D1CA2B2DA2320076E0EC /* DropDownFriends.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DropDownFriends.swift; sourceTree = "<group>"; };
ECB26A122B406A9400FE06B3 /* BetViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BetViewModel.swift; sourceTree = "<group>"; };
@ -390,6 +392,7 @@
EC01FCC22B56650400BB2390 /* DetailsViewModel.swift */,
EC01FCC42B56791B00BB2390 /* HistoricBetViewModel.swift */,
EC17A15F2B6A9781008A8679 /* CurrentBetViewModel.swift */,
EC9464E82B7413E1004EEBD8 /* BetEndingValidationViewModel.swift */,
);
path = ViewModels;
sourceTree = "<group>";
@ -557,6 +560,7 @@
ECB7BC702B336E28002A6654 /* RegisterViewModel.swift in Sources */,
EC17A1602B6A9781008A8679 /* CurrentBetViewModel.swift in Sources */,
EC650A4C2B25E9C7003AFCAD /* RankingView.swift in Sources */,
EC9464E92B7413E1004EEBD8 /* BetEndingValidationViewModel.swift in Sources */,
EC7A882B2B28D1E0004F226A /* DropDownMenu.swift in Sources */,
EC7A882D2B28D8A1004F226A /* CreationBetView.swift in Sources */,
ECED90B52B6D9CEC00F50937 /* DailyGiftPage.swift in Sources */,

@ -74,7 +74,5 @@ public struct BetApiManager: BetDataManager {
}
}
}.resume()
}
}

@ -47,7 +47,8 @@ public class FactoryApiBet: FactoryBet {
let endBetDateString = json["endBet"] as? String,
let isPublic = json["isPrivate"] as? Bool,
let createdBy = json["createdBy"] as? String,
let type = json["type"] as? String else {
let type = json["type"] as? String,
let status = json["status"] as? String else {
return nil
}
@ -56,7 +57,24 @@ public class FactoryApiBet: FactoryBet {
return nil
}
return toBet(id: id, theme: theme, description: phrase, endRegister: endRegisterDate, endBet: endBetDate, isPublic: isPublic, status: .finished, creator: User(username: createdBy, email: createdBy, nbCoins: 0, friends: []), type: type)
return toBet(id: id, theme: theme, description: phrase, endRegister: endRegisterDate, endBet: endBetDate, isPublic: isPublic, status: toStatus(status: status), creator: User(username: createdBy, email: createdBy, nbCoins: 0, friends: []), type: type)
}
func toStatus(status: String) -> BetStatus {
switch status {
case "IN_PROGRESS":
return .inProgress
case "WAITING":
return .waiting
case "CLOSING":
return .closing
case "FINISHED":
return .finished
case "CANCELLED":
return .cancelled
default:
return .finished
}
}
public func toBet(id: String, theme: String, description: String, endRegister: Date, endBet: Date, isPublic: Bool, status: BetStatus, creator: User, type: String) -> Bet {

@ -22,6 +22,37 @@ public struct UserApiManager: UserDataManager {
fatalError("Not implemented yet")
}
public func getBetsOver(completion : @escaping ([BetDetail])-> ()) {
let url = URL(string: allInApi + "bets/toConfirm")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
var bets: [BetDetail] = []
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
print ("ALLIN : get bets over")
do {
if let httpResponse = response as? HTTPURLResponse, let jsonArray = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] {
for json in jsonArray {
print(json)
if let bet = FactoryApiBet().toBetDetail(from: json) {
bets.append(bet)
}
}
print(httpResponse.statusCode)
completion(bets)
}
} catch {
print("Error parsing JSON: \(error)")
}
}
}.resume()
}
public func addBet(bet: Bet, completion : @escaping (Int)-> ()) {
let url = URL(string: allInApi + "bets/add")!
@ -54,7 +85,7 @@ public struct UserApiManager: UserDataManager {
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
print ("ALLIN : get gifts of the day")
@ -129,4 +160,26 @@ public struct UserApiManager: UserDataManager {
}.resume()
}
}
public func addResponse(withIdBet id: String, andResponse responseBet: String) {
let url = URL(string: allInApi + "bets/confirm/" + id)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
let json: [String: String] = [
"result": responseBet,
]
if let jsonData = try? JSONSerialization.data(withJSONObject: json, options: []){
URLSession.shared.uploadTask(with: request, from: jsonData) { data, response, error in
print ("ALLIN : add response " + responseBet + " for the bet Id " + id)
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.statusCode)
}
}.resume()
}
}
}

@ -28,6 +28,12 @@ public struct Manager {
}
}
public func getBetsOver(completion: @escaping ([BetDetail]) -> Void) {
userDataManager.getBetsOver() { bets in
completion(bets)
}
}
public func getBet(withId id: String, completion: @escaping (BetDetail) -> Void) {
betDataManager.getBet(withId: id) { bet in
completion(bet)
@ -52,6 +58,10 @@ public struct Manager {
}
}
public func addResponse(withIdBet id: String, andResponse response: String) {
userDataManager.addResponse(withIdBet: id, andResponse: response)
}
public func getTodayGifts(completion : @escaping (Int, Int)-> ()) {
userDataManager.getGifts() { status, gain in
completion(status, gain)

@ -9,10 +9,12 @@ import Foundation
public protocol UserDataManager {
func getBets(withIndex index: Int, withCount count: Int) -> [Bet]
func getBetsOver(completion: @escaping ([BetDetail]) -> Void)
func addBet(bet: Bet, completion : @escaping (Int)-> ())
func getFriends() -> [User]
func getGifts(completion : @escaping (Int, Int)-> ())
func getOldBets(withIndex index: Int, withCount count: Int, completion: @escaping ([Bet]) -> Void)
func getCurrentBets(withIndex index: Int, withCount count: Int, completion: @escaping ([Bet]) -> Void)
func addParticipation(withId id: String, withAnswer answer: String, andStake stake: Int, completion : @escaping (Int)-> ())
func addResponse(withIdBet id: String, andResponse responseBet: String)
}

Loading…
Cancel
Save