#include "framecpp/OOInterface/FrameH.hh"
#include "framecpp/OOInterface/FrEvent.hh"
#include "framecpp/OOInterface/FrSimEvent.hh"
#include "framecpp/OOInterface/OFrameFStream.hh"
#include "framecpp/OOInterface/IFrameFStream.hh"
#include <iostream>

int main() {
    const char* filename = "test_two_events.gwf";

    // Create a frame with 2 FrEvents
    {
        std::cerr << "=== Creating frame with 2 events ===" << std::endl;
        FrameCPP::OFrameFStream ofs(filename, 9); // version 9

        auto frame = boost::make_shared<FrameCPP::FrameH>();
        frame->SetName("TestFrame");
        frame->SetRun(1);
        frame->SetFrame(1);
        frame->SetGTimeS(1000000000);
        frame->SetGTimeN(0);
        frame->SetDt(1.0);

        // Create first event
        auto event1 = boost::make_shared<FrameCPP::FrEvent>();
        event1->SetName("TesT");
        event1->SetGTime(FrameCPP::GPSTime(1000000000, 100));
        event1->SetAmplitude(1.0);
        frame->AppendFrEvent(event1);
        std::cerr << "Added FrEvent 1" << std::endl;

        // Create second event
        auto event2 = boost::make_shared<FrameCPP::FrEvent>();
        event2->SetName("TesT");
        event2->SetGTime(FrameCPP::GPSTime(1000000000, 200));
        event2->SetAmplitude(2.0);
        frame->AppendFrEvent(event2);
        std::cerr << "Added FrEvent 2" << std::endl;

        // Create one sim event
        auto simevent = boost::make_shared<FrameCPP::FrSimEvent>();
        simevent->SetName("TesT");
        simevent->SetGTime(FrameCPP::GPSTime(1000000000, 300));
        simevent->SetAmplitude(3.0);
        frame->AppendFrSimEvent(simevent);
        std::cerr << "Added FrSimEvent 1" << std::endl;

        ofs.WriteFrame(frame);
        std::cerr << "Frame written" << std::endl;
    }

    // Read back and verify
    {
        std::cerr << "\n=== Reading frame back ===" << std::endl;
        FrameCPP::IFrameFStream ifs(filename);

        size_t event_count = 0;
        try {
            while (true) {
                ifs.ReadFrEvent("TesT", event_count);
                event_count++;
            }
        } catch (...) {}

        std::cerr << "Found " << event_count << " FrEvents (expected 2)" << std::endl;

        size_t simevent_count = 0;
        try {
            while (true) {
                ifs.ReadFrSimEvent("TesT", simevent_count);
                simevent_count++;
            }
        } catch (...) {}

        std::cerr << "Found " << simevent_count << " FrSimEvents (expected 1)" << std::endl;

        if (event_count == 2 && simevent_count == 1) {
            std::cerr << "\nSUCCESS: All events found!" << std::endl;
            return 0;
        } else {
            std::cerr << "\nFAILURE: Events missing!" << std::endl;
            return 1;
        }
    }
}
