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

#include <vcl.h>
#include <StrUtils.hpp>
#include <inifiles.hpp>
#pragma hdrstop

#include "imprimirTicket_main.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
#define min(a, b)  (((a) < (b)) ? (a) : (b)) 
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
        step = 0;
        importeCobrar = 0;
        importeEntrega = 0;
        serial_port_connected = false;
        importeTXT = "";


        /* Advance mode */
        /*
 Articulo/s                  Uds Importe
---------------------------- --- -------
        */

        sg->Cells[0][0] = "Articulo/s";
        sg->Cells[1][0] = "Uds";
        sg->Cells[2][0] = "Importe";


        /****************/

}
//---------------------------------------------------------------------------
void __fastcall TForm1::addToNumber(AnsiString number)
{
        if ( StrPos(importeTXT.c_str(), "," )==0 || number!="," )
                importeTXT += number;

        lcd->Caption = FormatFloat("#,##0.#0",importeTXT.ToDouble()) + " €";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::btIntroClick(TObject *Sender)
{
        switch( step )
        {
                case 0: stepLb->Caption = "Entrega:"; step++; lcd->Caption = "0.0 €"; importeCobrar = importeTXT.ToDouble(); importeEntrega = 0; importeTXT=""; break;
                case 1: stepLb->Caption = "Cambio:";  step++; importeEntrega = importeTXT.ToDouble(); lcd->Caption = FormatFloat("#,##0.#0", (importeEntrega-importeCobrar) )+" €"; break;
                case 2:
                default:
                        imprimirTicket(importeCobrar,importeEntrega);
                        stepLb->Caption = "Importe:"; step=0; lcd->Caption = "0.0 €"; importeCobrar = 0; importeTXT=""; break;
        }
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button14Click(TObject *Sender)
{
        addToNumber(",");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button13Click(TObject *Sender)
{
        addToNumber("0");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button11Click(TObject *Sender)
{
        addToNumber("3");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button10Click(TObject *Sender)
{
        addToNumber("2");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button9Click(TObject *Sender)
{
        addToNumber("1");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button7Click(TObject *Sender)
{
        addToNumber("6");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button6Click(TObject *Sender)
{
        addToNumber("5");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button5Click(TObject *Sender)
{
        addToNumber("4");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button3Click(TObject *Sender)
{
        addToNumber("9");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button2Click(TObject *Sender)
{
        addToNumber("8");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button1Click(TObject *Sender)
{
        addToNumber("7");
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Button4Click(TObject *Sender)
{
        importeTXT = "";
        lcd->Caption = "0,0 €";
        btIntro->SetFocus();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::imprimirTicket(float importeCobrar, float importeEntrega)
{
        if ( !serial_port_connected )
        {
                TIniFile *ini;
                ini = new TIniFile( ExtractFileDir( Application->ExeName ) + "\\cfg.ini" );
                puerto = ini->ReadString( "www.infdj.com", "PUERTO", "COM1" );
                ticket_numberSufix = ini->ReadString( "www.infdj.com", "ticket_numberSufix", "€" );

                ticket_header = new TStringList;
                ticket_header->CommaText = ini->ReadString( "www.infdj.com", "ticket_header", "" );
                ticket_footer = new TStringList;
                ticket_footer->CommaText = ini->ReadString( "www.infdj.com", "ticket_footer", "" );
                delete ini;

                serial_connect( puerto.c_str(),CBR_9600,NOPARITY,8,true );
        }

        AbreCajon();

        int i;
        for (i=0;i<ticket_header->Count;i++)
                serial_sendLine( ticket_header->Strings[i] );
        serial_sendLine( "Fecha: "+Now() );
        serial_sendLine( "" );
        serial_sendLine( Format( "Importe: %20s %s",ARRAYOFCONST(( FormatFloat("#,##0.#0", importeEntrega), ticket_numberSufix )) ) );
        serial_sendLine( "" );
        serial_sendLine( "------------------------------" );
        serial_sendLine( Format( "Entrega: %20s %s",ARRAYOFCONST(( FormatFloat("#,##0.#0", importeEntrega), ticket_numberSufix )) ) );
        serial_sendLine( Format( "Cambio:  %20s %s",ARRAYOFCONST(( FormatFloat("#,##0.#0", (importeEntrega-importeCobrar)), ticket_numberSufix )) ) );
        serial_sendLine( "------------------------------" );
        for (i=0;i<ticket_footer->Count;i++)
                serial_sendLine( ticket_footer->Strings[i] );
}
// --------------------------------------------------------------------------
void __fastcall TForm1::AbreCajon()
{
        char b[15];

        b[0]=(char)0x1B;        b[1]='p';        b[2]=0;        b[3]=127;        b[4]=127;
        serial_sendData( b,5 );
}
//---------------------------------------------------------------------------
int __fastcall TForm1::serial_sendLine(AnsiString data)
{
        data = "\r\n"+data;
        return serial_sendData( data.c_str(), data.Length() );
}
//---------------------------------------------------------------------------
int __fastcall TForm1::serial_sendData(char *data,int length)
{
/*
  int i,dev=-1;
  for(i=0;dev!=0 && i<length;i++)
          dev=TransmitCommChar( serial_hCom, data[i] );
*/
  unsigned long int wt;
  return WriteFile( serial_hCom,data,length,&wt,NULL);
//  return dev;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::serial_disconnect()
{
  if ( serial_port_connected )
  {
          CloseHandle( serial_hCom );
          serial_hCom=0;
  }
  serial_port_connected = false;
}
//---------------------------------------------------------------------------
//, 9600, SERIAL_PARITY_NONE, 8, true);
void __fastcall TForm1::serial_connect(const char *port, int BaudRate,int Parity,char ByteSize, bool excl)
{
  if ( serial_port_connected ) serial_disconnect();

//  HANDLE serial_hCom;
  serial_hCom = CreateFile( port,
                     GENERIC_READ | GENERIC_WRITE,
                     0,    // comm devices must be opened w/exclusive-access
                     NULL, // no security attributes
                     OPEN_EXISTING, // comm devices must use OPEN_EXISTING
                     0,    // not overlapped I/O
                     NULL  // hTemplate must be NULL for comm devices
                     );

  if (serial_hCom != INVALID_HANDLE_VALUE)
  {
    if ( port[0]=='L' )
    {
            serial_port_connected = true;
    } else {
            DCB dcb;
            // We will build on the current configuration, and skip setting the size
            // of the input and output buffers with SetupComm.
            if ( GetCommState(serial_hCom, &dcb) )
            {

              // Fill in the DCB: baud=57,600 bps, 8 data bits, no parity, and 1 stop bit.
              dcb.BaudRate = BaudRate;//CBR_1200;     // set the baud rate
              dcb.ByteSize = ByteSize;//8;             // data size, xmit, and rcv
              dcb.Parity = Parity;//NOPARITY;        // no parity bit
              dcb.StopBits = ONESTOPBIT;    // one stop bit

              if ( !SetCommState(serial_hCom, &dcb) )
                      CloseHandle( serial_hCom );
              else
                      serial_port_connected = true;
        //        TransmitCommChar( hCom, 0xFF );
            }
    }
  }
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormKeyPress(TObject *Sender, char &Key)
{
  if ( PageControl1->ActivePage == TabSheet2 ) return;

        switch( Key )
        {
                case '.': addToNumber(","); break;
                case '0': addToNumber("0"); break;
                case '1': addToNumber("1"); break;
                case '2': addToNumber("2"); break;
                case '3': addToNumber("3"); break;
                case '4': addToNumber("4"); break;
                case '5': addToNumber("5"); break;
                case '6': addToNumber("6"); break;
                case '7': addToNumber("7"); break;
                case '8': addToNumber("8"); break;
                case '9': addToNumber("9"); break;
                case '+': lcd->Caption = "0.0 €"; importeTXT=""; break;
                case VK_RETURN: btIntroClick(NULL); break;
        }
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormDestroy(TObject *Sender)
{
  if ( serial_port_connected )
  {
          serial_disconnect();
          delete ticket_header;
          delete ticket_footer;
  }
}
//---------------------------------------------------------------------------


void __fastcall TForm1::sgKeyPress(TObject *Sender, char &Key)
{
  if ( Key==VK_RETURN ) {
          sg->Col = (sg->Col + 1)%3;
          if ( sg->Col == 0 ) sg->Row = min(sg->Row+1,6);
  }
}
//---------------------------------------------------------------------------

void __fastcall TForm1::SpeedButton1Click(TObject *Sender)
{
        if ( !serial_port_connected )
        {
                TIniFile *ini;
                ini = new TIniFile( ExtractFileDir( Application->ExeName ) + "\\TPV.ini" );
                puerto = ini->ReadString( "TPV", "puertoImpresoraPOS", "COM1" );

                delete ini;

                serial_connect( puerto.c_str(),CBR_9600,NOPARITY,8,true );
        }

        AbreCajon();

        char b[15];
//        b[0]=(char)0x1B; b[1]='!'; b[2]=0x01; // Negrita
        b[0]=(char)0x1B; b[1]='r'; b[2]='0'; serial_sendData( b,3 ); // Color Negro
        b[0]=(char)0x1B; b[1]='a'; b[2]='0';  serial_sendData( b,3 ); // Alinear IZQUIERDA


        int i;
        for (i=0;i<Memo1->Lines->Count;i++)
                serial_sendLine( Memo1->Lines->Strings[i] );

        serial_sendLine( " Articulo/s                  Uds Importe" );
        serial_sendLine( "---------------------------- --- -------" );

        float importe, importeTotal;
        importeTotal = 0;
        for ( i=1; i<sg->RowCount; i++ ) {
          if ( !sg->Cells[0][i].IsEmpty() ) {
                try { importe = AnsiReplaceStr( sg->Cells[2][i], ".", "," ).ToDouble(); } catch(...) { importe = 0; }
                serial_sendLine( Format( "%28s %-3s %s",ARRAYOFCONST(( sg->Cells[0][i],sg->Cells[1][i], FormatFloat("#,##0.#0", importe ) )) ) );
                importeTotal += importe;
          }
        }

        serial_sendLine( "" );
        serial_sendLine( Format( "Importe: %20s %s",ARRAYOFCONST(( FormatFloat("#,##0.#0", importeTotal), ticket_numberSufix )) ) );

        for (i=0;i<Memo2->Lines->Count;i++)
                serial_sendLine( Memo2->Lines->Strings[i] );
}
//---------------------------------------------------------------------------

void __fastcall TForm1::PageControl1Change(TObject *Sender)
{
  if ( PageControl1->ActivePage == TabSheet2 ) sg->SetFocus();       
}
//---------------------------------------------------------------------------

