//---------------------------------------------------------------------------


#pragma hdrstop

#include "dbDm.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma classgroup "Vcl.Controls.TControl"
#pragma resource "*.dfm"
#include "c_poruka.h"
#include <IdGlobal.hpp>
#include <System.SysUtils.hpp>
#include <System.hpp>
Tdb *db;
AnsiString 	LOG_FAJL 		= GetCurrentDir() + "\\Log\\" + Sysutils::ExtractFileName(Sysutils::ChangeFileExt(Application->ExeName, ""))  + ".log"  ;//;//        = APP_DIR + "\\Log\\CashIT\\" + Sysutils::ExtractFileName(Sysutils::ChangeFileExt(Application->ExeName, ""))  + ".log"  ;//Sysutils::ChangeFileExt(Application->ExeName, ".log");
AnsiString 	LOG_FAJL1 		= GetCurrentDir() + "\\Log\\" + Sysutils::ExtractFileName(Sysutils::ChangeFileExt(Application->ExeName, ""))  + ".log1"  ;
int VELICINA_LOG_FAJLA=900;
//---------------------------------------------------------------------------
__fastcall Tdb::Tdb(TComponent* Owner)
	: TDataModule(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall Tdb::openMlekaraCds(){
	cdsMlekara->Active = false;
	cdsMlekara->Active = true;
}
void __fastcall Tdb::Timer1Timer(TObject *Sender)
{
	openMlekaraCds();
}
//---------------------------------------------------------------------------
void __fastcall Tdb::Timer2Timer(TObject *Sender)
{
	ClientDataSet1->Active = false;
	ClientDataSet1->Active = true;

	ClientDataSet2->Active = false;
	ClientDataSet2->Active = true;

	ClientDataSet3->Active = false;
	ClientDataSet3->Active = true;

	ClientDataSet4->Active = false;
	ClientDataSet4->Active = true;

}
//---------------------------------------------------------------------------
int __fastcall Tdb::SnimiCDS(TClientDataSet* cds, TSQLConnection* sc)
{
    TTransactionDesc TD;
	TD.TransactionID  = 1;
	TD.IsolationLevel = 1;
	if (sc->InTransaction)
	{
		sc->Commit(TD);
    }
    OleVariant MasterVar, OwnerData;
	int ErrCount = 0;

	if (cds->OnPostError == NULL ) {
//		cds->OnPostError =  DM->cdsHostPostError;
	}


    cds->CheckBrowseMode();

	if (cds->ChangeCount > 0)
		MasterVar = cds->Delta;
    else
		MasterVar.ChangeType(VT_NULL);

    try
    {

        if (!sc->InTransaction)
        {
			sc->StartTransaction(TD);

            try
            {
                if (!MasterVar.IsNull())
                {
                    ErrCount = cds->ApplyUpdates(0);
					if (ErrCount > 0)
                    {
						LogError(cds , "Broj gresaka=" + IntToStr(ErrCount) + " " + cds->Name, 0) ;
						throw Exception("Broj gresaka=" + IntToStr(ErrCount) + " " + cds->Name);
                    }
				}
            }
            catch (Exception& e)
            {
                if (sc->InTransaction)
                    sc->Rollback(TD);
                PosaljiPoruku("Greska snimanja!! " + e.Message);
            }

            if (sc->InTransaction)
            {
                if (ErrCount == 0)
                {
					sc->Commit(TD);
                }
                else
                {
                    sc->Rollback(TD);
                }
            }
        }
    }
    catch (Exception& e)
    {
		if (sc->InTransaction)
            sc->Rollback(TD);
		PosaljiPoruku("Greska snimanja!! " + e.Message);
    }

	if (ErrCount > 0) {
		cds->Reconcile(MasterVar);


	}

	return 0;
}

void __fastcall Tdb::PosaljiPoruku(AnsiString poruka)
{
    Tfrm_poruka* frm_poruka = new Tfrm_poruka(poruka, Application);
    frm_poruka->Show();
    Application->ProcessMessages();

}

void __fastcall Tdb::LogError(TCustomClientDataSet* DataSet, AnsiString poruka, int posalji_poruku)
{
//	ScreenCaptureJPG("frmMP.jpg");

	AnsiString greska;
	AnsiString forma = DataSet->Owner->Name;
	greska           = DateTimeToStr(Now()) + " - DataSet: " + DataSet->Name + " -Radnik: - Greska: ";

	UpisiULogFile(LOG_FAJL, "-pocetak-", 2);
	UpisiULogFile(LOG_FAJL, poruka, 2);
	UpisiULogFile(LOG_FAJL, greska, 2);
	NamestiInsert( DataSet, DataSet->Name) ;
	UpisiULogFile(LOG_FAJL, "-kraj-", 2);


	if (posalji_poruku == 1)
	{
		PosaljiPoruku("Greska: ");
	}

}

void __fastcall Tdb::UpisiULogFile(AnsiString filename, AnsiString text, int pocetak)
{
	char szFileName[300];
	char cr;
	char* pszBuffer;
	int velicina_fajla;
	int iFileHandle;
	int iPom;
	// HANDLE iFileHandle;
	text = DateTimeToStr(Now()) + " Radnik: -  " + text;
	int iLength,
		iFileLength;
		//iBytesRead;	/* defined but never used */
	AnsiString duzina, pom_fajl;
	if (filename == "")
	{
		filename = FormatDateTime("yymmddhhmm", Now()) + ".txt";
	}

	if (FileExists(filename))
	{
		iFileHandle    = FileOpen(filename, fmOpenReadWrite);
		iFileLength    = FileSeek(iFileHandle, 0, 2);
//		velicina_fajla = FileSizeByName(filename);
//		if (velicina_fajla > VELICINA_LOG_FAJLA * 1000)
//		{
//			FileClose(iFileHandle);
//			pom_fajl = Sysutils::ChangeFileExt(Application->ExeName, ".log1");
//			CopyFileTo(filename, pom_fajl);
//			DeleteFile(filename);
//			iFileHandle = FileOpen(filename, fmOpenReadWrite);
//			iFileLength = FileSeek(iFileHandle, 0, 2);
//		}
		FileSeek(iFileHandle, 0, pocetak);
		if (pocetak == 0) // dodajes na pocetak fajla
		{
			// otvoris pomocni file
			iPom = FileCreate("pom" + filename, fmOpenReadWrite);
			// upises sta treba da je na pocetku fajla
			FileWrite(iPom, text.c_str(), text.Length());
			cr = 13;
			FileWrite(iPom, & cr, 1);
			cr = 10;
			FileWrite(iPom, & cr, 1);
			pszBuffer  = new char[iFileLength + 1]; // kopiras stari sadrzaj na pomocni file
			//iBytesRead = 	/* defined but never used */
			FileRead(iFileHandle, pszBuffer, iFileLength);
			FileClose(iFileHandle);
			FileWrite(iPom, pszBuffer, iFileLength);
			FileClose(iPom);
			delete[]pszBuffer;
			DeleteFile(filename);
			CopyFileTo("pom" + filename, filename);
			DeleteFile("pom" + filename);
			return;
		}
	}
	else
	{
		iFileHandle = FileCreate(filename);
	}
	iLength = text.Length();
	duzina = IntToStr(iLength);
	duzina += "@";

	// FileWrite(iFileHandle, duzina.c_str(), duzina.Length());

	FileWrite(iFileHandle, text.c_str(), text.Length());
	cr = 13;
	FileWrite(iFileHandle, & cr, 1);
	cr = 10;
	FileWrite(iFileHandle, & cr, 1);

	FileClose(iFileHandle);
}

void __fastcall Tdb::NamestiInsert( TCustomClientDataSet *DataSet, AnsiString imeTabele)
{
  //
	if (DataSet->Active == true)
	{
		int broj_polja = DataSet->FieldCount;
		AnsiString insert1 = "(";
		AnsiString insert2 = "VALUES (";
		for (int i = 0; i < broj_polja; i++)
		{
			insert1 = insert1 + DataSet->Fields->Fields[i]->FieldName;
			if (i <broj_polja-1) {
            	insert1 = insert1 + ",";
			}
			if (i == broj_polja-1) {
				insert1 = insert1 + ")";
			}

			if ( DataSet->Fields->Fields[i]->DataType == ftString ||
				 DataSet->Fields->Fields[i]->DataType == ftTimeStamp ||
				 DataSet->Fields->Fields[i]->DataType == ftDate ) {

				if (DataSet->Fields->Fields[i]->IsNull) {
					insert2 = insert2 + "NULL";
				}
				else
					insert2 = insert2 + "'" + DataSet->Fields->Fields[i]->AsString + "'";
			}
			else {
				if (DataSet->Fields->Fields[i]->IsNull) {
					insert2 = insert2 + "NULL";
				}
				else {
					insert2 = insert2 +  DataSet->Fields->Fields[i]->AsString ;
                }
			}
			if (i <broj_polja-1) {
            	insert2 = insert2 + ",";
			}
			if (i == broj_polja-1) {
				insert2 = insert2 + ")";
			}

		}
		UpisiULogFile(LOG_FAJL, "INSERT INTO " + imeTabele, 2);
		UpisiULogFile(LOG_FAJL, insert1, 2);
		UpisiULogFile(LOG_FAJL, insert2, 2);
	}
}
