//Renata Kopecna


#include "ReferencePlots.hh"

#include <vector>

#include "ScriptHelpers.hh"
#include <bu2kstarmumu_parameters.hh>
#include <paths.hh>
#include <helpers.hh>

#include <TColor.h>
#include <TH2D.h>
#include <TCanvas.h>
#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>

#include <spdlog.h>

const int oneSigma_RGB[3]   = {34,136,51};
const int twoSigma_RGB[3]   = {170,170,0};
const int threeSigma_RGB[3] = {238,22,136};
const int moreSigma_RGB[3]  = {204,51,17};

//TODO: make it into a texfile instead of a cout!

const std::vector<valErr> Davids = {
    valErr(+0.572,0.005),//valErr(+0.321,0.004),
    valErr(-0.002,0.007),
    valErr(-0.246,0.008),
    valErr(-0.003,0.008),
    valErr(-0.002,0.005),//valErr(-0.003,0.006),
    valErr(-0.001,0.008),
    valErr(-0.063,0.008),
    valErr(-0.084,0.007)
};
const std::vector<valErr> Belles = {
    valErr(+0.604,0.015),//valErr(+0.297,0.011),
    valErr(-0.018,0.017),
    valErr(-0.255,0.010),
    valErr(0.0,0.0),
    valErr(0.0,0.0),
    valErr(0.0,0.0),
    valErr(-0.037,0.018),
    valErr(-0.041,0.016)
};
const std::vector<valErr> BaBars = {
    valErr(+0.556,0.009),//valErr(+0.333,0.007),
    valErr(+0.011,0.011),
    valErr(-0.237,0.007),
    valErr(0.0,0.0),
    valErr(0.0,0.0),
    valErr(0.0,0.0),
    valErr(-0.058,0.015),
    valErr(-0.095,0.014)
};
const std::vector<valErr> B0s = {
    valErr(+0.572,0.008),//valErr(+0.321,0.006),
    valErr(-0.013,0.010),
    valErr(-0.250,0.006),
    valErr(0.0,0.0),
    valErr(0.0,0.0),
    valErr(0.0,0.0),
    valErr(-0.048,0.007),
    valErr(-0.084,0.006)
};

std::vector<double>getSigma(std::vector<valErr> vec_a, std::vector<valErr> vec_b){
    if (vec_a.size() != vec_b.size()){
        spdlog::error("Two valErr vectors have different lenghts! Abort.");
        assert(0);
    }
    std::vector<double>sigs;
    for_indexed(auto a: vec_a){
        sigs.push_back(sigmaAway(a,vec_b[i]));
    }
    return sigs;
}

std::vector<const int*>getSigmaColor(std::vector<double>vec_sigma){
    std::vector<const int*> tmp;
    for(auto sigma: vec_sigma){
        if (fabs(sigma) < 1.0) tmp.push_back(oneSigma_RGB);
        else if (fabs(sigma)  < 2.0) tmp.push_back(twoSigma_RGB);
        else if (fabs(sigma)  < 3.0) tmp.push_back(threeSigma_RGB);
        else tmp.push_back(moreSigma_RGB);
    }
    return tmp;
}

std::string getSigmaColor_str(double sigma){
    if (fabs(sigma) < 1.0) return "\\cellcolor{oneSigma}";
    else if (fabs(sigma) < 2.0) return "\\cellcolor{twoSigmas}";
    else if (fabs(sigma) < 3.0) return"\\cellcolor{threeSigmas}";
    else return "\\cellcolor{moreSigmas}";
}

std::vector<std::string>getSigmaColor_strVec(std::vector<double>vec_sigma){
    std::vector<std::string> tmp;
    for(auto sigma: vec_sigma) tmp.push_back(getSigmaColor_str(sigma));
    return tmp;
}
double getCorrectedError(std::string name, double err, int jobID){ //For now, no bins, cause it is used anyhow only for reference //TODO

    basic_params tmpParams; //This is dumb, but no time
    tmpParams.jobID = jobID;

    std::string fileName = get_ToyPullPlot_folder(tmpParams)+"pullResults.root";
    spdlog::info("Opening " + fileName);
    TFile* file = new TFile(fileName.c_str(), "READ");

    if (!file->GetListOfKeys()->Contains(name.c_str())){
        spdlog::critical("Wrong tree name " + name + "! Abort.");
        assert(0);
    }
    //Get the tree and set the branches to active
    TTree* tree = (TTree*)file->Get(name.c_str());
    tree->SetBranchStatus("*",1); //Activate all branches
    double width = DEFAULT_TREE_ERR;
    double mean  = DEFAULT_TREE_VAL;

    tree->SetBranchAddress("width", &width);
    tree->SetBranchAddress("mean", &mean);

    tree->GetEntry(0);
    file->Close();

    //get_param_valueError_from_rootfile()

    return err*width;
}

int plotComparisonFull(){
    spdlog::debug("Starting with printing the values for RefChan measurement in a nice table.");
    double fractionOfStats = 1.0;

    basic_params params_Fit= basic_params();
    params_Fit.Run = 12;
    params_Fit.nBins = 1;
    params_Fit.reference =true;
    std::string fitFile = final_result_name(true, false, params_Fit,
                                            true, 1, params_Fit.Run,
                                            false, fractionOfStats,
                                            false, -1);

    std::vector<valErr> myValues;
    spdlog::debug("Filling my values into a vector");
    for (auto obs: ANG_OBS){
        //The easiest rounding in c++
        double err = get_param_error_from_rootfile(fitFile, obs, 1,0);
        //The easiest rounding in c++
        err = round(getCorrectedError(obs,err,649)*1000.0)/1000.0;     //TODO
        double val = round(get_param_value_from_rootfile(fitFile, obs, 1,0)*1000.0)/1000.0;
        myValues.push_back(valErr(val,err));
    }
    std::vector<std::string>col_Davids = getSigmaColor_strVec(getSigma(myValues,Davids));
    std::vector<std::string>col_Belles = getSigmaColor_strVec(getSigma(myValues,Belles));
    std::vector<std::string>col_BaBars = getSigmaColor_strVec(getSigma(myValues,BaBars));
    std::vector<std::string>col_B0s = getSigmaColor_strVec( getSigma(myValues,B0s));

    std::cout << "\\begin{table}[]" << std::endl;
    std::cout << "\\begin{tabular}{llllll}" << std::endl;
    std::cout << " & this fit & \\lhcb \\Bu & Belle (\\Bu) & BaBar (\\Bu + \\Bd) & \\lhcb \\Bd \\\\\\hline" << std::endl;
    for_indexed(auto myVal: myValues){
        std::cout << std::setprecision(3) << "$" << ANG_OBS_TLaTeX[i] << "$";
        std::cout << " & " << myVal.val << "$\\pm$" <<myVal.err;
        std::cout << " & " << col_Davids[i] << " " << Davids[i].val << "$\\pm$" <<Davids[i].err;
        std::cout << " & " << col_Belles[i] << " " << Belles[i].val << "$\\pm$" <<Belles[i].err;
        std::cout << " & " << col_BaBars[i] << " " << BaBars[i].val << "$\\pm$" <<BaBars[i].err;
        std::cout << " & " << col_B0s[i] << " " << B0s[i].val << "$\\pm$" <<B0s[i].err;
        std::cout << "\\\\" << std::endl;
    }

    std::cout << " \\end{tabular}" << std::endl;
    std::cout << " \\end{table}" << std::endl;

    return 0;
}




int foldingTable(){
    spdlog::debug("Starting with printing the values for different foldings RefChan measurement in a nice table.");
    double fractionOfStats = 1.0;

    basic_params params_Fit= basic_params();
    params_Fit.Run = 12;
    params_Fit.nBins = 1;
    params_Fit.reference =true;

    std::cout << "\\begin{table}[]" << std::endl;
    std::cout << "\\begin{tabular}{l|"; //First cell is for the obs name
    for (int f = -1; f<MAX_FOLDING; f++) std::cout << "l";
    std::cout << "}" << std::endl;
    std::cout << std::setprecision(1) << " & No folding" ;
    for (int f = 0; f<MAX_FOLDING; f++) std::cout << " & Folding " << f;
    std::cout <<"\\\\\\hline" << std::endl;

    for_indexed (auto obs: ANG_OBS){ //TODO: if it would be for me, this would be a struct of name and latexname
        std::cout << std::setprecision(3) << "$" << ANG_OBS_TLaTeX[i] << "$";
        params_Fit.folding = -1; //Needed extra as it has to be saved to myVec to get the sigmas away
        std::string fitFile = final_result_name(true, false, params_Fit,
                                                true, 1, params_Fit.Run,
                                                false, fractionOfStats,
                                                false, -1);
        //The easiest rounding in c++
        double err = get_param_error_from_rootfile(fitFile, obs, 1,0);
        //The easiest rounding in c++
        err = round(getCorrectedError(obs,err,649)*1000.0)/1000.0;     //TODO

        double val = round(get_param_value_from_rootfile(fitFile, obs, 1,0)*1000.0)/1000.0;
        valErr full(err,val);
        std::cout << " & " << val << "$\\pm$" << err;

        for (int f = 0; f<MAX_FOLDING; f++){
            if (plotObsv(f,obs)){
                params_Fit.folding = f;
                int jobID = 626+params_Fit.folding;
                if (params_Fit.folding==4) jobID = 650;

                std::string fitFile = final_result_name(true, false, params_Fit,
                                                        true, 1, params_Fit.Run,
                                                        false, fractionOfStats,
                                                        false, -1);

                //The easiest rounding in c++
                double err = get_param_error_from_rootfile(fitFile, obs, 1,0);
                //The easiest rounding in c++
                err = round(getCorrectedError(obs,err,jobID)*1000.0)/1000.0;
                double val = round(get_param_value_from_rootfile(fitFile, obs, 1,0)*1000.0)/1000.0;

                std::cout << " & " << getSigmaColor_str(sigmaAway(full,valErr(err,val))) << val << "$\\pm$" << err;
            }
            else std::cout << " &          ";
        }
        std::cout << "\\\\" << std::endl;
    }

    std::cout << " \\end{tabular}" << std::endl;
    std::cout << " \\end{table}" << std::endl;

    return 0;
}

int plotComparisonSigmas(){
    spdlog::debug("Starting with printing the values for RefChan measurement in a nice table.");
    double fractionOfStats = 1.0;

    basic_params params_Fit= basic_params();
    params_Fit.Run = 12;
    params_Fit.nBins = 1;
    params_Fit.reference =true;
    std::string fitFile = final_result_name(true, false, params_Fit,
                                            true, 1, params_Fit.Run,
                                            false, fractionOfStats,
                                            false, -1);

    std::vector<valErr> myValues;
    spdlog::debug("Filling my values into a vector");
    for (auto obs: ANG_OBS){
        double err = get_param_error_from_rootfile(fitFile, obs, 1,0);
        //The easiest rounding in c++
        err = round(getCorrectedError(obs,err,649)*1000.0)/1000.0;     //TODO
        double val = round(get_param_value_from_rootfile(fitFile, obs, 1,0)*1000.0)/1000.0;
        myValues.push_back(valErr(val,err));
    }
    std::vector<double>sig_Davids = getSigma(myValues,Davids);
    std::vector<double>sig_Belles = getSigma(myValues,Belles);
    std::vector<double>sig_BaBars = getSigma(myValues,BaBars);
    std::vector<double>sig_B0s = getSigma(myValues,B0s);

    std::cout << "\\begin{table}[]" << std::endl;
    std::cout << "\\begin{tabular}{l|llll}" << std::endl;
    std::cout << " &  \\lhcb \\Bu & Belle (\\Bu) & BaBar (\\Bu + \\Bd) & \\lhcb \\Bd \\\\\\hline" << std::endl;
    //for_indexed(auto myVal: myValues){ //TODO remove: yields warning in compilation due to unused 'myVals'
    for(UInt_t i = 0; i < sig_Davids.size(); i++){
        std::cout << std::setprecision(2) << "$" << ANG_OBS_TLaTeX[i] << "$";
        std::cout << " & " << sig_Davids[i];
        std::cout << " & " << sig_Belles[i];
        std::cout << " & " << sig_BaBars[i];
        std::cout << " & " << sig_B0s[i];
        std::cout << "\\\\" << std::endl;
    }

    std::cout << " \\end{tabular}" << std::endl;
    std::cout << " \\end{table}" << std::endl;

    return 0;
}


