import SwiftUI

struct EcaMenuView: View {
    @ObservedObject var taskViewModel: TaskViewModel
    @ObservedObject var ecaData = SharingData.eca
    @Environment(\ .colorScheme) var colorScheme
    @State var isDeleteAlert: Bool = false
    let deleteEcaArea = DeleteEcaArea()
    var eca: RegisteredEca

    var body: some View {
        Menu {
            Text(eca.name)

            Button{
                taskViewModel.edittingEcaArea = eca
                taskViewModel.ecaName = eca.name
                taskViewModel.viewMode = .EcaSetting
            } label: {
                Text("Edit Notice Setting")
            }

            Button{
                taskViewModel.edittingEcaArea = eca
                taskViewModel.ecaName = eca.name
                isDeleteAlert = true
            } label: {
                Text("Delete ECA Task")
            }
        } label: {
            Image(systemName: "ellipsis")
                .frame(width: 22, height: 22)
                .opacity(eca.isRunning == true ? 0.2 : 1.0)
                .foregroundColor(colorScheme == .light ? .black : .white)
        }
        .disabled(eca.isRunning)
        .alert("Delete", isPresented: $isDeleteAlert) {
            Button("Yes") {
                if let ecaArea = taskViewModel.edittingEcaArea {
                    var newData = ecaArea
                    newData.isEnable = false
                    newData.status = EcaState.cancel

                    ecaData.editEcaArea(key: ecaArea.areaId, value: newData, type: EcaOperation.Delete)
                    deleteEcaArea.start(ecaId: ecaArea.areaId)
                }
                taskViewModel.edittingEcaArea = nil
            }
            Button("No"){}
        } message: {
            Text("Have you finished " + taskViewModel.ecaName + " fuel switching?")
        }
    }
}
