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

import SwiftUI
import Combine

struct NetworkModifier: ViewModifier {
    @ObservedObject private var networkMonitor = NetworkMonitor.shared
    @EnvironmentObject var alertController: AlertController
    
    func body(content: Content) -> some View {
        content
            .onChange(of: networkMonitor.isConnected) { _ , new in
                if !new {
                    alertController.alertData = SetAlertData().setErrorNetwork()
                    alertController.showAlert.toggle()
                }
            }
    }
}

struct AlertModifier: ViewModifier {
    @EnvironmentObject var controller: AlertController
    func body(content: Content) -> some View {
        content
            .alert(controller.alertData.title,
                   isPresented: $controller.showAlert,
                   presenting: $controller.alertData) { data in
                let btnCount = data.button.count
                ForEach(0 ..< btnCount, id: \.self) { index in
                    let btn = data.wrappedValue.button[index]
                    Button(role: btn.role) {
                        if let function = btn.function { function() }
                    } label: {
                        Text("\(btn.name)")
                    }
                }
            } message: { data in
                Text("\(data.body.wrappedValue)")
            }
    }
}

extension View {
    func fullView(_ backColor: Color) -> some View {
        return self
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(backColor)
    }
    
    func setAlert() -> some View {
        self.modifier(AlertModifier())
    }
    func setNetwork() -> some View {
        self.modifier(NetworkModifier())
    }
    
    func endTextEditing() {
            UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    }
    
    func setNavigaion() -> some View {
        self
            .navigationBarBackButtonHidden(true)
            .toolbar(.hidden, for: .navigationBar)
    }
}
