//
//  ContentView.swift
//  ToneShaperPreview
//
//  Created by Joseph Pagliaro on 12/7/23.
//

import SwiftUI
import AVFoundation

class AudioPlayerManager: ObservableObject {
    var audioPlayer: AVAudioPlayer?
    
    func playAudio(from url: URL) {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.play()
        } catch {
            print("Error playing audio: \(error.localizedDescription)")
        }
    }
}

struct PlayButtonView: View {
    
    @StateObject var audioPlayerManager = AudioPlayerManager()
    
    var body: some View {
        Button(action: {
            
            if let audioURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("ToneShape.wav")  {
                audioPlayerManager.playAudio(from: audioURL)
            }
            
        }) {
            VStack {
                Image(systemName: "play.circle.fill")
                    .font(.system(size: 18))
                    .foregroundColor(.blue)
                
                Text("Play")
                    .foregroundColor(.blue)
            }
        }
    }
}

struct ContentView: View {
    
    @State private var selection = 1
    
    let plotter = IntegrationPlotter()
    let audioPlotter = AudioPlotter(useSimpsons: kUseSimpsons)
    
    @State var plotter_paths = [Path(), Path(), Path()]
    @State var audio_paths = [Path(), Path()]
    
    @State var plotActualIntegral = true
    
    func updatePlotterPaths(frameSize: CGSize) {
        plotter_paths = GeneratePath(a: 0, b: 1, N: 10000, frameSize: frameSize, inset: 10, graphs: [plotter.instantaneous_frequency(_:), plotter.sampling_argumemt(_:), plotter.actual_integral(_:)])
    }
    
    func updateAudioPaths(frameSize: CGSize) {
        audio_paths = GeneratePath(a: 0, b: 1, N: 30000, frameSize: frameSize, inset: 10, graphs: [audioPlotter.instantaneous_frequency(_:), audioPlotter.audio_samples(_:)])
    }
    
    var body: some View {
        TabView(selection: $selection) {
                // Tab 1 for IntegrationPlotter
            GeometryReader { geometry in
                ZStack(alignment: .bottomLeading) {
                    plotter_paths[0]
                        .stroke(Color.blue, lineWidth: 2)
                    
                    plotter_paths[1]
                        .stroke(Color.red, lineWidth: 4)
                    
                    if plotActualIntegral {
                        plotter_paths[2]
                            .stroke(
                                Color.white,
                                style: StrokeStyle(
                                    lineWidth: 1,
                                    lineCap: .round,
                                    lineJoin: .round,
                                    dash: [5, 5]
                                )
                            )
                    }
                    
                    Toggle("Plot sin(2 π t)/(2 π)", isOn: $plotActualIntegral)
                        .padding()
                }
                .onAppear {
                    updatePlotterPaths(frameSize: geometry.size)
                }
                .onChange(of: geometry.size) { _ in
                    updatePlotterPaths(frameSize: geometry.size)
                }
            }
            .tabItem {
                Label("Integrate cos(2 π t)", systemImage: "sum")
            }
            .tag(0)
            
                // Tab 2 for AudioPlotter
            GeometryReader { geometry in
                ZStack {
                    audio_paths[0]
                        .stroke(Color.blue, lineWidth: 2)
                    
                    audio_paths[1]
                        .stroke(Color.red, lineWidth: 1)
                    
                    PlayButtonView()
                }
                .onAppear {
                    updateAudioPaths(frameSize: geometry.size)
                }
                .onChange(of: geometry.size) { _ in
                    updateAudioPaths(frameSize: geometry.size)
                }
            }
            .tabItem {
                Label("ToneShape Audio", systemImage: "waveform")
            }
            .tag(1)
        }
        .padding()
        .onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                selection = 0
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
