//
//  LiveTimerView.swift
//  LeCountdown
//
//  Created by Laurent Morvillier on 03/02/2023.
//

import SwiftUI

struct LiveTimerView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    @EnvironmentObject var conductor: Conductor
    
    @State var timer: AbstractTimer
    var date: Date
    
    var body: some View {
        HStack {
            Text(timer.displayName.uppercased()).padding()

            Spacer()
            TimelineView(.periodic(from: self.date, by: 0.01)) { context in
                Text(self._formattedDuration(date: context.date))
                    .font(.title2)
                    .padding(.trailing)
                    .minimumScaleFactor(0.1)
            }
            
            Button {
                self._stopTimer(timer)
            } label: {
                Image(systemName: "xmark.circle.fill")
                    .font(.title)
                    .foregroundColor(.white)
                    .cornerRadius(8.0)
                    .frame(minWidth: 0.0, maxWidth: 60.0, minHeight: 0.0, maxHeight: .infinity)
            }.background(.red)
        }
    }
    
    fileprivate func _formattedDuration(date: Date) -> String {
        if self.timer is Stopwatch {
            let duration = date.timeIntervalSince(self.date)
            return duration.hourMinuteSecondHS
        } else { // countdown
            let duration = self.date.timeIntervalSince(date)
            return duration.minuteSecond
        }
    }
    
    fileprivate func _stopTimer(_ timer: AbstractTimer?) {
        
        guard let timer else {
            return
        }
        
        TimerRouter.stopTimer(timer: timer)
        
    }
    
}

struct LiveTimerListView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    @EnvironmentObject var conductor: Conductor
    
    var body: some View {
        LazyVStack {
            ForEach(conductor.liveTimers) { liveTimer in
                
                if let timer: AbstractTimer = liveTimer.timer(context: self.viewContext) {
                    
                    LiveTimerView(timer: timer, date: liveTimer.date)
                        .frame(height: 55.0)
                        .foregroundColor(.white)
                        .monospaced()
                        .background(Color(white: 0.2))
                        .cornerRadius(16.0)
                }
                
            }
        }.padding(8.0)
        
    }
    
    
}

struct LiveTimerView_Previews: PreviewProvider {
    
    init() {
        Conductor.maestro.currentCountdowns["fef"] = DateInterval(start: Date(), end: Date())
    }
    
    static var previews: some View {
        LiveTimerListView().environmentObject(Conductor.maestro)
    }
}
