//
//  NavigationView.swift
//  AcaMate
//
//  Created by Sean Kim on 12/12/24.
//

import SwiftUI
import Combine



struct NavigationView: View {
    @State private var naviState : NaviState = .init(act: .NONE, path: .Intro)
    @State private var history: [PathName] = [.Intro]

    
    var body: some View {
        ZStack {
            switch naviState.path {
            case .NONE:
                EmptyView()
            case .Intro:
                IntroView(naviState: $naviState)
            case .Login :
                LoginView(naviState: $naviState)
            case .Main:
                EmptyView()
            }
        }
        .onChange(of: naviState) { old, new in
            switch new.act {
            case .NONE:
                break
            case .ADD:
                addHistory(path: new.path)
            case .POP:
                popHistory()
            case .RESET:
                resetHistory(path: new.path)
            case .MOVE:
                moveHistory(path: new.path)
            }
            
            // LOG
            printLog("\(old.path) => \(new.path)")
            showHistory()
        }
        .fullView(.Normal.normal)
        .setAlert()
        .setNetwork()
    }
    
    private func addHistory(path: PathName) {
        history.append(path)
    }
    
    private func popHistory() {
        history.removeLast()
        naviState.set(act: .NONE, path: history.last ?? .NONE)
    }
    
    private func resetHistory(path: PathName) {
        history.removeAll()
        addHistory(path: path)
    }
    
    private func moveHistory(path: PathName) {
        if path == .NONE {
            naviState.set(act: .RESET, path: history.first ?? .Main)
        }
        if history.contains(path) {
            let remove = history.count - history.firstIndex(of: path)! - 1
            history.removeLast(remove)
            if remove > 0 {
                naviState.set(act: .NONE, path: path)
                return
            }
        }
        naviState.set(act: .RESET, path: path)
    }
    
    private func showHistory() {
        printLog(history)
    }
    
}
