#include <applicat.h>
#include <automask.h>
#include <isam.h>
#include <recarray.h>
#include <progind.h>

// File
#include <fstream>
#include <string>

#include "ba7500a.h"

#define FILE_AGG "nazioni2017.txt"


class TStati_mask : public TAutomask
{
protected:
  virtual bool on_field_event(TOperable_field& o, TField_event e, long jolly);
	void fill();
public:
	TStati_mask() : TAutomask("ba7500a") { fill(); };
	~TStati_mask() {};
	TString saveRec();
};

bool TStati_mask::on_field_event(TOperable_field& o, TField_event e, long jolly)
{
	return true;
}

void TStati_mask::fill()
{
	TSheet_field& sheet = sfield(F_STATI);
	TString_array& strarr = sheet.rows_array();
	sheet.hide();

	// Aggiungo a mano (sigh) gli stati
	strarr.add("735|ANTARTIDE|AQ");
	strarr.add("736|ARUBA|AW");
	strarr.add("737|ISOLE ALAND|AX");
	strarr.add("738|BARBADOS|BB");
	strarr.add("739|SAINT-BARTHELEMY|BL");
	strarr.add("740|ISOLE BES|BQ");
	strarr.add("741|ISOLA BOUVET|BV");
	strarr.add("742|BOTSWANA|BW");
	strarr.add("743|CURACAO|CW");
	strarr.add("744|GIBUTI|DJ");
	strarr.add("745|SAHARA OCCIDENTALE|EH");
	strarr.add("746|GUERNSEY|GG");
	strarr.add("747|GEORGIA DEL SUD|GS");
	strarr.add("748|ISOLE HEARD E MCDONALD|HM");
	strarr.add("749|TERRITORI BRITANNICI DELL'OCEANO INDIANO|IO");
	strarr.add("750|JERSEY|JE");
	strarr.add("751|KIRIBATI|KI");
	strarr.add("752|LESOTHO|LS");
	strarr.add("753|MAROCCO|MA");
	strarr.add("754|MONTENEGRO|ME");
	strarr.add("755|SAINT-MARTIN|MF");
	strarr.add("756|MALESIA|MY");
	strarr.add("757|NUOVA ZELANDA|NZ");
	strarr.add("758|STATO DI PALESTINA|PS");
	strarr.add("759|PALAU|PW");
	strarr.add("760|SERBIA|RS");
	strarr.add("761|RUSSIA|RU");
	strarr.add("762|SVALBARD (ISOLE)|SJ");
	strarr.add("763|JAN MAYEN|SJ");
	strarr.add("764|SUDAN DEL SUD|SS");
	strarr.add("765|SINT MAARTEN|SX");
	strarr.add("766|TERRITORI FRANCESI DEL SUD|TF");
	strarr.add("767|TURKMENISTAN|TM");
	strarr.add("768|TANZANIA|TZ");
	strarr.add("769|ISOLE MINORI ESTERNE DEGLI STATI UNITI D'AMERICA|UM");
	strarr.add("770|VANUATU|VU");
	strarr.add("771|YEMEN|YE");

	sheet.force_update();
	sheet.show();
}

TString TStati_mask::saveRec()
{
	TSheet_field& sheet = sfield(F_STATI);
	TLocalisamfile fStati(LF_TABCOM);
	TString ret;
	FOR_EACH_SHEET_ROW(sheet, r, strarr)
	{
		TString codtab = strarr->get(0);
		TString s0 = strarr->get(1);
		TString s10 = strarr->get(2);
		if(codtab != "")
		{
			// Cerco se esiste il record
			TRectype rowStati = cache().get("%STA", codtab);
			rowStati.put("CODTAB", codtab);
			rowStati.put("S0", s0);
			rowStati.put("S10", s10);
			if(fStati.write_rewrite(rowStati) != NOERR)
				ret << "ERRORE cod: " << codtab << " nazione: " << s0 << "\n";
		}
	}
	return ret;
}

class TStati_app : public TSkeleton_application
{ 
protected:
	TString update(TStati_mask& m);
	int lineQty();
public:
  virtual void main_loop();
};

TString TStati_app::update(TStati_mask& m)
{
	ifstream aggStati(FILE_AGG, std::ifstream::in);
	TLocalisamfile tabcom(LF_TABCOM);
	TString ret;
	// Aggiorno prima con il file ba7500.txt
	if (aggStati.is_open())
  {
    TLocalisamfile tabcom(LF_TABCOM);
		TToken_string row;
		
		TProgress_monitor p(lineQty(), "Aggiornamento dati");
		string line;
		while(std::getline(aggStati, line))
		{
			if (!p.add_status())
				break;
			row = line.c_str();
			TString cod = row.get(0);
			TString codtab = row.get(1);
			TString s0 = row.get(2);
			TString val = row.get(4);

			if(cod == "STA")
				bool tolla = true;


			TRectype rowStati = cache().get(cod == "STA" ? "%STA" : "%SCE", codtab);
			rowStati.put("COD", cod);
			rowStati.put("CODTAB", codtab);
			rowStati.put("S0", s0);
			rowStati.put(cod == "STA" ? "S10" : "B0", val);

			if(tabcom.write_rewrite(rowStati) != NOERR)
				ret << "ERRORE nazione: " << codtab << " tipo: " << cod << "\n";
		}
  }
	else
		return "ERRORE: non trovo il file " FILE_AGG;

	// Adesso aggiorno gli stati secondo la maschera
	return ret << m.saveRec();
}

int TStati_app::lineQty()
{
	int n = 0;
    FILE *infile = fopen(FILE_AGG, "r");
    int ch;

    while (EOF != (ch=getc(infile)))
        if ('\n' == ch)
            ++n;
		return n;
}

void TStati_app::main_loop()
{
	TStati_mask m;
	TString html;
  html << "<html><body>"
        << "<p align=justify>Questo programma trasformer� la tabella degli stati CEE nella tabella stati ISO 3166-1 alpha-2"
				<< " e creer� un collegamento con la tabella delle nazioni.<br />"
				<< "Alcune nazioni non sono presenti nelle tabelle precaricate, qui di sotto verranno proposte"
				<< " con dei codici progressivi. Se alcune di queste fossero gi� state inserite manualmente"
				<< " vi invitiamo a modificare il codice consigliato con quello da voi scelto.<br />"
				<< "Rispondendo \"OK\" apparir� una ricerca che vi aiuter� a controllare la corrispondenza.</p><br />"
        << "</body></html>";

#ifndef DBG
	message_box(html);
#endif

	while(m.run() == K_ENTER)
	{
		TString res = update(m);
		if(res.empty())
			res = "Aggiornato correttamente!";
		message_box(res);
			
	}
}


int ba7500(int argc, char* argv[])
{  
  TStati_app ma;
  ma.run(argc, argv, "Aggiornamento stati");
  return 0;
}