//Create tables of BDT significance for B+->Kst+mumu
//david gerick

#include "../../GlobalFunctions.hh"
#include "../../HeidelbergFitter/LHCbStyle.h"

//#include "MVA_b2kmm.cc"

using namespace std;
using namespace RooFit ;

//////////////////////////////////////////////////////
///  GetMVASignificance()
///   

void GetMVASignificance(std::vector<Int_t> Run, std::vector<std::string> DDLL, std::string BDTmethod) {

  bool debug = false;

  UInt_t NN = Run.size();
  assert(NN == DDLL.size());

  std::vector< std::vector<int> > rank;
  std::vector< std::vector< std::string> > latex_name;
  std::vector< std::vector<float> > value;

  for(UInt_t n = 0; n < NN; n++){

    std::cout << "[LOAD]\t\tRun" << Run.at(n) << " " << DDLL.at(n) << std::endl;


    //load MVAconfig
    MVA_variables vars(DDLL.at(n)); 

    rank.push_back(std::vector<int>());
    latex_name.push_back(std::vector<std::string>());
    value.push_back(std::vector<float>());

    //load results from .txt (This has to be saved manually from the MVA training output, before creating the LaTeX table)
    std::ifstream file;
    std::string line = "";
    std::string filename = path_to_data+"/"+BDTmethod+"results_Run"+std::to_string(Run.at(n))+DDLL.at(n)+".txt";
    file.open(filename);
    if (file.is_open()){
      std::cout << "[INFO]\t\tOpened the result file: " << filename << std::endl;
      std::cout << "[INFO]\t\tProceed with loading the results!" << std::endl;
    }
    else{
      std::cout << "[ERROR]\t\tCould not load the result file: " << filename << std::endl;
      std::cout << "[ERROR]\t\tMake sure, the result from the MVA training are copied (by hand) into the *.txt file" << std::endl;
      std::cout << "[ERROR]\t\tThe part that needs to be copied looks something like this:" << std::endl;
      std::cout << "[ERROR]\t\t" << std::endl;
      for(UInt_t i = 0; i < 8; i++)
        std::cout << "[ERROR]\t\t--- " << BDTmethod << "              :   " << i+1 << " : variable" << i+1 << " : value" << std::endl;
      return;
    }

    while(1){ //loop over lines until you find the end of the file
        getline(file, line);
        if(file.eof()) break;
        if(line.length() == 0)continue;

        size_t first_colon = line.find(":");
        if(first_colon == line.length())continue;
        size_t secon_colon = line.find(":", first_colon+1);
        if(secon_colon == line.length())continue;
        size_t third_colon = line.find(":", secon_colon+1);
        if(third_colon == line.length())continue;

        if(debug){ 
          std::cout << "Line: '" << line << "'\twith length=" << line.length() << std::endl;
          std::cout << "First ':' at pos=" << first_colon << "\tSecond ':' at pos=" << secon_colon << "\tThird ':' at pos=" << third_colon << std::endl;
        }

        //save the rank
        rank.at(n).push_back(atoi(line.substr(first_colon+1, secon_colon-first_colon-2).c_str()));
        std::string branch_name = line.substr(secon_colon+2, third_colon-secon_colon-2);
        while(replace(branch_name, " ", ""));
        while(replace(branch_name, "log_", ""));

        //convert and save the LaTeX name
        Int_t var = 0;
        while(var < vars.NumberOfVariables()){
            if(vars.AllVariables.at(var).ReaderName.find(branch_name.c_str()) < vars.AllVariables.at(var).ReaderName.length())
            break;
          var++;
        }
        if(var == vars.NumberOfVariables()){
          std::cout << "[ERROR]\t\tNo LaTeX name found for varialbe: '" << branch_name << "'" << std::endl;
          return;
        }
        latex_name.at(n).push_back(vars.AllVariables.at(var).LaTeXName);
        while(replace(latex_name.at(n).back(), "K_{s}^{0}", "\\KS "));
        while(replace(latex_name.at(n).back(), "K_{s}", "\\KS "));
        while(replace(latex_name.at(n).back(), "B^{+}", "\\Bu "));
        while(replace(latex_name.at(n).back(), "#chi^{2}", "\\chisq "));
        while(replace(latex_name.at(n).back(), "#mu^{+}", "\\mup "));
        while(replace(latex_name.at(n).back(), "#mu^{-}", "\\mun "));
        while(replace(latex_name.at(n).back(), "K^{*+}", "\\Kstarp "));
        while(replace(latex_name.at(n).back(), "#pi^{+}", "\\pip "));
        while(replace(latex_name.at(n).back(), "p_{T}", "\\pt "));
        while(replace(latex_name.at(n).back(), "#eta", "$\\eta$"));
        while(replace(latex_name.at(n).back(), "#", "\\"));
//        while(replace(latex_name.at(n).back(), "", ""));

        //save the MVA significance value (in %)
        value.at(n).push_back(atof(line.substr(third_colon+2).c_str())*100.);
    }

    assert(rank.at(n).size() == latex_name.at(n).size());
    assert(rank.at(n).size() == value.at(n).size());

    if(debug){
      for(UInt_t i = 0; i < rank.at(n).size(); i++){
        std::cout << "#" << rank.at(n).at(i) << ": " << latex_name.at(n).at(i) << " = " << Form("%.2f", value.at(n).at(i)) << std::endl;
      }
    }

    file.close();

  }


    //print LaTeX table:
    std::cout << std::endl << std::endl << std::endl;
    std::cout << "\\begin{center}\\begin{tabular}{";
    for(UInt_t n = 0; n < NN; n++)
      std::cout << "lr";
    std::cout << "} \\hline" << std::endl;
    for(UInt_t n = 0; n < NN; n++){
      if(n != 0)
        std::cout << "\t&";
      std::cout << "Run " << Run.at(n);
      if(DDLL.at(n) != "")
       std::cout << " \\" << DDLL.at(n);
      std::cout << "\t&[\\\%]";
    }
    std::cout << "\\\\" << std::endl;
    std::cout << "\\hline" << std::endl;
    for(UInt_t v = 0; v < rank.at(0).size(); v++){
      for(UInt_t n = 0; n < NN; n++){
        if(n != 0)
          std::cout << "\t&";
        if(latex_name.at(n).size() > v)
          std::cout << latex_name.at(n).at(v) << "\t&" << Form("%.2f", value.at(n).at(v));
        else
          std::cout << "\t &";
      }
      std::cout << "\\\\" << std::endl;
    }
    std::cout << "\\hline" << std::endl;
    std::cout << "\\end{tabular}\\end{center}" << std::endl;
    std::cout << std::endl << std::endl << std::endl;
    return;
}

void GetAllMVATables(){

  std::string method = std::string(TMVAmethod);

  if(Kst2Kspiplus){
    GetMVASignificance({1, 1}, {"DD", "LL"}, method);
    GetMVASignificance({2, 2}, {"DD", "LL"}, method);
  }
  else{
    GetMVASignificance({1, 2}, {"",""}, method);
  }
}

