//
//  IntroView.swift
//  AcaMate
//
//  Created by Sean Kim on 12/1/24.
//

import SwiftUI
import Combine

struct IntroView: View {
    @EnvironmentObject var appVM: AppViewModel
    
    @State var cancellables: Set<AnyCancellable> = []
    @Binding var naviState : NaviState
    
    var body: some View {
        VStack(spacing: 0) {
            Spacer()
                .frame(height: 100)
            Image(.Logo.appIcon)
                .resizable()
                .frame(width: 200, height: 200)
            Spacer()
            HStack(spacing: 4) {
                Image(.Logo.teamIcon)
                    .resizable()
                    .frame(width: 24, height: 24)
                Text("STEIN")
                    .font(.nps(font: .bold, size: 16))
                    .foregroundStyle(Color(.Text.detail))
            }
            .padding(.bottom,12)
            Text("Copyright © Team.Stein")
                .font(.nps(font: .regular, size: 14))
                .foregroundStyle(Color(.Text.detail))
                .padding(.bottom,50)
        }
        
        .onAppear {
            printLog("IntroView_onAppear")
            #if LOCAL
            naviState.set(act: .RESET, path: .Login)
            #else
            subscribeAlertAction()
            loadVersion()
                .sink { completion in
                    switch completion {
                    case .failure(let error):
                        printLog(error)
                    case .finished: break
                    }
                } receiveValue: { version in
                    @UserDefault(key:"currentVer", defaultValue: "0.0.0") var currentVer
                    @UserDefault(key:"finalVer", defaultValue: "0.0.0") var finalVer
                    currentVer = currentVersion()
                    finalVer = version.final_ver
                    
                    let compareForce = compareVersion(version.force_ver, currentVer)//currentVersion())
                    let compareChoice = compareVersion(version.final_ver, currentVer)//currentVersion())
                    
                    if compareForce == .bigger {
                        appVM.alertData = SetAlertData().setForceUpdate(
                            action: appVM.alertAction
                        )
                        appVM.showAlert.toggle()
                    } else if compareChoice == .bigger && version.choice_update_yn {
                        appVM.alertData = SetAlertData().setSelectUpdate(
                            action: appVM.alertAction
                        )
                        appVM.showAlert.toggle()
                    } else {
                        // 정상 동작 넘어감
                        naviState.set(act: .RESET, path: .Login)
                        
                        
                    }
                }
                .store(in: &cancellables)
            #endif
            
        }
    }
    
    private func subscribeAlertAction() {
        appVM.alertAction
            .compactMap { $0 }
            .sink { action in
                if action == "updateNow" {
                    exit(1)
                    //MARK: - TODO (앱스토어 이동 로직 넣을 것)
                } else {
                    naviState.set(act: .RESET, path: .Login)
                }
            }.store(in: &cancellables)
    }
    
    
    private func loadVersion() -> Future<VersionData, Error> {
        return Future { promise in
            loadAPIData(url: "\(API_URL)",
                        path: "/api/v1/in/app/version",
                        parameters: ["type":"I"],
                        decodingType: APIResponse<VersionData>.self)
            .sink { completion in
                switch completion {
                case .failure(let error):
                    printLog("\(error)")
                    promise(.failure(error))
                case .finished: break
                }
            } receiveValue: { data in
                guard let apiData = data as? APIResponse<VersionData> else {return}
                printLog("\(apiData.data.toStringDict())")
                promise(.success(apiData.data))
            }
            .store(in: &cancellables)
        }
        
    }
    
    private func currentVersion() -> String {
        guard let currentVer = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else { return "" }
        return currentVer
        
    }
    
    private func versionChange(ver: String) -> [Int] {
        return ver.components(separatedBy: ["."]).map {Int($0) ?? 0}
    }
}
