#include <pulse/simple.h>
#include <pulse/error.h>
#include <cmath>
#include <thread>
#include <atomic>
#include <iostream>

std::atomic<bool> running{true};
float gfreq=440;

void playTone(float freq, float durationSec) {
    const int sample_rate = 44100;

    pa_sample_spec ss;
    ss.format = PA_SAMPLE_FLOAT32LE;
    ss.rate = sample_rate;
    ss.channels = 1;

    int error;
    pa_simple *s = pa_simple_new(
        nullptr,
        "ToneGenerator",
        PA_STREAM_PLAYBACK,
        nullptr,
        "Playback",
        &ss,
        nullptr, nullptr,
        &error
    );

    if (!s) {
        std::cerr << "PulseAudio error: " << pa_strerror(error) << "\n";
        return;
    }

    int total_samples = durationSec * sample_rate;

    for (int i = 0; i < total_samples && running; i++) {
        float sample = sinf(2.0f * M_PI * gfreq * i / sample_rate);

        if (pa_simple_write(s, &sample, sizeof(sample), &error) < 0) {
            std::cerr << "pa_simple_write() failed: " << pa_strerror(error) << "\n";
            break;
        }
    }

    pa_simple_drain(s, &error);
    pa_simple_free(s);
}

int main() {
    std::cout << "Starting tone in background...\n";

    std::thread t([](){
        playTone(440.0f, 5.0f);   // 5 seconds in background
    });

    // Main program continues running
    std::cout << "Main program is free to do other work...\n";

    // Simulate work
    //std::this_thread::sleep_for(std::chrono::seconds(2));
    //std::cout << "Still running...\n";

    for(int i1=0; i1<10; i1++)
    {
      usleep(1000000/2);
      gfreq+=100;
    }

    t.join();
    std::cout << "Tone finished.\n";
}
