#include "MCaos.h"

#include <iostream>
#include <iomanip>

#include <TSystem.h>
#include <TFile.h>
#include <TTree.h>
#include <TH1.h>
#include <TH2.h>
#include <TGraph.h>
#include <TCanvas.h>

#include "Led.h"
#include "Ring.h"
#include "Rings.h"
#include "FilterLed.h"

#include "coord.h"
#include "base/timer.h"

void MCaos::ReadResources(const char *name="leds.txt")
{
    ifstream fin(name);
    if (!fin)
    {
        cout << "ERROR - Cannot open " << name << endl;
        return;
    }

    fPositions.Clear();

    cout << " Reading " << name << ":" << endl;
    cout << "------------------------------" << endl;

    while (1)
    {
        Double_t px, py, ox, oy;
        fin >> px >> py >> ox >> oy;
        if (!fin)
            break;

        cout << " Led #" << fPositions.GetEntriesFast() << ":  ";
        cout << setw(3) << px << " ";
        cout << setw(3) << py << "  (";
        cout << setw(3) << ox << ", ";
        cout << setw(3) << oy << ")" << endl;
        AddPosition(px, py, ox, oy);
    }
    cout << "Found " << fPositions.GetEntriesFast() << " leds." << endl;
}

void MCaos::OpenFile()
{
    int i=0;
    char name[100];
    while (1)
    {
        sprintf(name, "data/data%03d.root", i++);
        if (gSystem->AccessPathName(name, kFileExists))
            break;
    }

    if (fFile)
        delete fFile;

    fFile = new TFile(name, "RECREATE");

    if (!fFile->IsOpen())
    {
        delete fFile;
        fFile = NULL;

        cout << "Error: Cannot open file '" << name << "'" << endl;
    }

    TTree *tree = new TTree("Data", "Real CaOs Data");

    fLeds = new Leds;
    fEvtTime = 0;

    tree->Branch("Leds", "TClonesArray", &fLeds);
    tree->Branch("ZenithDist.", &fZenithDist, "fZenithDist/D");
    tree->Branch("Azimuth.",    &fAzimuth,    "fAzimuth/D");
    tree->Branch("EvtTime.",    &fEvtTime,    "fEvtTime/D");

    cout << "Root file '" << name << "' open." << endl;
}

void MCaos::CloseFile()
{
    if (!fFile)
        return;

    const TString  name = fFile->GetName();
    const Double_t n    = ((TTree*)fFile->Get("Data"))->GetEntries();

    fFile->Write();
    delete fFile;
    fFile = NULL;

    cout << "Root file closed (n=" << n << ")" << endl;

    if (n<1)
    {
        gSystem->Unlink(name);
        cout << "Root file deleted - no entries." << endl;
    }
}

void MCaos::InitHistograms()
{
    if (fHistpr)
        return;

    Rings r;
    r.CalcRings(fPositions);

    const Ring &c = r.GetCenter();

    Double_t xmin = c.GetX()-50;
    Double_t xmax = c.GetX()+50;

    Double_t ymin = c.GetY()-50;
    Double_t ymax = c.GetY()+50;

    Double_t rmin = c.GetR()-50;
    Double_t rmax = c.GetR()+50;

    Int_t xbin = 1001;
    Int_t ybin = 1001;
    Int_t rbin = 1001;

    const Int_t sz = 50;
    fHistled = new TH2F*[fPositions.GetEntriesFast()];
    fHistw   = new TH1F*[fPositions.GetEntriesFast()];
    for (int i=0; i<fPositions.GetEntriesFast(); i++)
    {
        TString name  = "LED";
        TString title = "LED #";

        name += i;
        title += i;

        const Led &p = fPositions(i);
        fHistled[i] = new TH2F(name, title,
                               20*sz+1, p.GetX()-sz, p.GetX()+sz,
                               20*sz+1, p.GetY()-sz, p.GetY()+sz);
        fHistled[i]->SetXTitle("x [pix]");
        fHistled[i]->SetYTitle("counts");

        name = "Angle";
        title = "Angle of the Led #";

        name += i;
        title += i;

        fHistw[i] = new TH1F;
        fHistw[i]->SetNameTitle(name, title);
        fHistw[i]->SetBins(721, -180.5, 180.5);
        fHistw[i]->SetXTitle("\\Phi [deg]");
        fHistw[i]->SetYTitle("counts");
    }

    fHistallw = new TH1F;
    fHistallw->SetNameTitle("allw","Rotation angel");
    fHistallw->SetBins(26, -25, 25);
    fHistallw->SetXTitle("\\Phi [arcmin]");
    fHistallw->SetYTitle("counts");

    fHistprxpry = new TH2F;
    fHistprxpry->SetNameTitle("prx und pry","x- and y-coordniate of the ring-center");
    fHistprxpry->SetBins(xbin, xmin, xmax, ybin, ymin, ymax);
    fHistprxpry->SetXTitle("x [mm]");
    fHistprxpry->SetYTitle("y [mm]");
    fHistprxpry->SetZTitle("counts");

    fGraphprx = new TGraph;
    fGraphprx->SetTitle("time-developement of the x-coordinate of the ring-center");

    fGraphpry = new TGraph;
    fGraphpry->SetTitle("time-developement of the y-coordinate of the ring-center");

    fGraphw = new TGraph*[fPositions.GetEntriesFast()];
    for (int i=0; i<fPositions.GetEntriesFast(); i++)
    {
        TString title = "Time-developement of the angle ";
        title += i;

        fGraphw[i] = new TGraph;
        fGraphw[i]->SetTitle(title);
    }

    fHistpr = new TH1F("pr","Radius of the ring", rbin, rmin, rmax);
    fHistpr->SetXTitle("r [pix]");
    fHistpr->SetYTitle("counts");
}

void MCaos::DeleteHistograms()
{
    TH1F *dummy = fHistpr;
    fHistpr=NULL;

    if (!dummy)
        return;

    delete dummy;
    delete fHistprxpry;
    delete fHistallw;
    delete fGraphprx;
    delete fGraphpry;

    for (int i=0; i<6; i++)
    {
        delete fHistled[i];
        delete fHistw[i];
        delete fGraphw[i];
    }
    delete fHistled;
    delete fHistw;
}

void MCaos::ShowHistograms()
{
    if (!fHistpr || fHistpr->GetEntries()<1)
        return;

    TH1 *h;

    TCanvas *c = new TCanvas("cring", "Center of the ring", 800, 800);
    c->Divide(2,2);
    c->cd(1);
    h = (TH1*)fHistprxpry->ProfileX();
    h->Fit("gaus");
    h->Draw();
    h->SetBit(kCanDelete);
    c->cd(2);
    h = (TH1*)fHistprxpry->ProfileY();
    h->Fit("gaus");
    h->Draw();
    h->SetBit(kCanDelete);
    c->cd(3);
    fHistpr->Fit("gaus");
    fHistpr->DrawCopy();
    c->cd(4);
    fHistprxpry->DrawCopy(/*"surf2"*/);
    c->Update();

    const Int_t n1 = (Int_t)(sqrt(fPositions.GetEntriesFast())+1.0);
    const Int_t n2 = (Int_t)(sqrt(fPositions.GetEntriesFast())+0.5);

    TCanvas *c1 = new TCanvas("cpos", "Led Positions", 800, 600);
    TCanvas *c2 = new TCanvas("cangle", "Angles of the Leds", 800, 600);
    c1->Divide(n1, n2);
    c2->Divide(n1, n2);
    for (int i=0; i<fPositions.GetEntriesFast(); i++)
    {
        c1->cd(i+1);
        fHistled[i]->DrawCopy();
        c2->cd(i+1);
        fHistw[i]->DrawCopy();
    }
    c1->Update();
    c2->Update();

    c = new TCanvas("ctime", "timedevelopement of center", 800, 800);
    c->Divide(1,2);
    c->cd(1);
    h = fGraphprx->GetHistogram();
    h->SetXTitle("time [s]");
    h->SetYTitle("x [pix]");
    h->DrawCopy();
    //fGraphprx->DrawClone("LP*")->SetBit(kCanDelete);
    c->cd(2);
    h = fGraphpry->GetHistogram();
    h->SetXTitle("time [s]");
    h->SetYTitle("y [pix]");
    h->DrawCopy();
    //fGraphpry->DrawClone("LP*")->SetBit(kCanDelete);
    c->Modified();
    c->Update();

    /* --------------------------------------------------------
     *  CALCULATE OFFSETS!
     * --------------------------------------------------------
     Rings r;
     r.CalcRings(fPositions);

     const Ring &c = r.GetCenter();
     */
}

void MCaos::ResetHistograms()
{
    if (!fHistpr)
        return;

    fHistpr->Reset();
    fHistprxpry->Reset();
    fHistallw->Reset();
    for (int i=0; i<6; i++)
    {
        fHistled[i]->Reset();
        fHistw[i]->Reset();
    }
}

void MCaos::Run(byte *img, bool printl, bool printr, const ZdAz &pos, const Timer &t)
{
    Leds &leds = *fLeds;
    leds.Clear();

    //          img  width height radius sigma
    FilterLed f(img, 768, 576, 50, 3.0);

    Int_t first=0;
    for (int i=0; i<fPositions.GetEntriesFast(); i++)
    {
        // Try to find Led in this area
        const Led &l0 = fPositions(i);
        f.Execute(leds, l0.GetX(), l0.GetY());

        // Loop over newly found Leds
        for (int j=first; j<leds.GetEntries(); j++)
        {
            Led &l1 = leds(j);

            // Add Offset to Led
            l1.AddOffset(l0.GetDx(), l0.GetDy());

            // Mark Led in image (FIXME: Move to MStarguider)
            f.MarkPoint(l1.GetX(), l1.GetY(), l1.GetMag());

            // Fill values into Histogram
            if (!fHistpr)
                continue;

            fHistled[i]->Fill(l1.GetX(), l1.GetY());
            fHistw[i]->Fill(l1.GetPhi());
        }
        first = leds.GetEntries();
    }

    Rings rings;
    rings.CalcRings(leds, 266, 272);

    const Ring &center = rings.GetCenter();

    f.DrawCircle(center, 0x80);
    f.DrawCircle(center,   5.0, 0x80);
    f.DrawCircle(center, 115.0, 0x80);
    f.DrawCircle(center, 190.0, 0x80);
    // f.MarkPoint(center.GetX(), center.GetY(), 0xa0);

    // FIXME!
    static const Timer t0(t);
    fEvtTime = (double)t-(double)t0;

    if (fHistpr)
    {
        fHistpr->Fill(center.GetR());
        fHistprxpry->Fill(center.GetX(), center.GetY());
        fGraphprx->SetPoint(fGraphprx->GetN(), fEvtTime, center.GetX());
        fGraphpry->SetPoint(fGraphpry->GetN(), fEvtTime, center.GetY());
    }

    if (printl)
        leds.Print();
    if (printr)
        rings.Print();

    if (fFile && leds.GetEntries()>0)
    {
        fZenithDist = pos.Zd(); //fCosy ? fCosy->GetPointingPos().Zd() : 0
        fAzimuth    = pos.Az(); //fCosy ? fCosy->GetPointingPos().Az() : 0;

        TTree *t = (TTree*)fFile->Get("Data");
        t->Fill();
    }

    /*
        if (fCaosAnalyse->IsEntryEnabled(IDM_kStopAnalyse))
        {
            const Ring &center = rings.GetCenter();

            Double_t phi[6] =
            {
                -124.727,
                 -61.0495,
                 -16.7907,
                  49.3119,
                 139.086
            };

            Double_t sum = 0;
            for (int i=0; i<6 && leds.At(i); i++)
            {
                const Double_t w = (leds(i).GetPhi()-phi[i])*60;

                sum += w;

                fHistw[i]->Fill(w);
                fHistv[i]->Fill(leds(i).GetPhi());
                fGraphw[i]->SetPoint(fGraphw[i]->GetN(), fEvtTime, w);
            }
            fHistallw->Fill(sum/5);
            }
            */
}

