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

#include <vcl.h>
#include <inifiles.hpp>

#pragma hdrstop

#include "TMain.h"
#include "configurador.h"
#include "screenTV.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "DigitNum"
#pragma link "DigitNum"
#pragma resource "*.dfm"
Tmain *main;
//---------------------------------------------------------------------------
#define min(a, b)  (((a) < (b)) ? (a) : (b))
#define max(a, b)  (((a) > (b)) ? (a) : (b))  
//---------------------------------------------------------------------------
__fastcall Tmain::Tmain(TComponent* Owner)
        : TForm(Owner)
{

  // Creamos un array de 5 Filas x 8 columnas...

  int i,j;
  filas = PROD_ROWS;
  columnas = PROD_COLS;
  char buffer[1024];

  pvp = new TProds[filas*columnas];
  
  TIniFile *pIniFile = new TIniFile(ExtractFileDir(Application->ExeName)+"\\preciometro.ini");
  fuenteLCD = pIniFile->ReadString("cfg","fnt",ExtractFileDir(Application->ExeName)+"\\fnt\\FUTURA-2.FNT");


  TVx = pIniFile->ReadInteger("cfg","TVx",1024);
  TVy = pIniFile->ReadInteger("cfg","TVy",0);
  TVm = pIniFile->ReadBool("cfg","TVm",true);


  // cargamos desde archivo, la configuración para cada producto...
  for (i=0; i<(filas*columnas);i++ )
  {
        pvp[i].descr = pIniFile->ReadString("pvp","descr"+AnsiString(i),"Nuevo Producto"+AnsiString(i));
        pvp[i].imagen = pIniFile->ReadString("pvp","imagen"+AnsiString(i),ExtractFileDir(Application->ExeName)+"\\images\\box.jpg");

        pvp[i].PVPmax = pIniFile->ReadString("pvp","PVPmax"+AnsiString(i),"0").ToDouble();
//        pvp[i].PVPcurr = pIniFile->ReadString("pvp","PVPcurr"+AnsiString(i),"2,9").ToDouble();
        pvp[i].PVPcurr = pvp[i].PVPmax;

        pvp[i].PVPmin = pIniFile->ReadString("pvp","PVPmin"+AnsiString(i),"0").ToDouble();

        pvp[i].nclicks = pIniFile->ReadInteger("pvp","nclicks"+AnsiString(i),100);
        pvp[i].clicks = pIniFile->ReadInteger("pvp","clicks"+AnsiString(i),1);
  }

  delete pIniFile;


  int idx;
  try {                                         // TEST FOR EXCEPTIONS.
        productos = new TImage* [filas*columnas];           // STEP 1: SET UP THE ROWS.
        etiquetas = new TLabel* [filas*columnas];           // STEP 1: SET UP THE ROWS.

        for (j = 0; j < filas; j++)
        {
          for (i=0; i<columnas; i++)
          {
            idx = j*columnas+i;
            productos[idx] = new TImage(this);

            producto = productos[idx];
            producto->Left = 24 + (81+17)*i;
            producto->Top = 117 + (89+20)*j;

            producto->AutoSize = false;
            producto->Stretch = true;
            producto->Proportional = true;
            producto->Width = 81;
            producto->Height = 89;

            producto->Tag = idx;
            producto->Picture->LoadFromFile(pvp[idx].imagen);

            producto->OnMouseMove = MouseMove;
            producto->OnClick = Click;

            this->InsertControl(producto);


            etiqueta = new TLabel(this);
            etiquetas[idx] = etiqueta;

            etiqueta->Left = producto->Left;
            etiqueta->Top = producto->Top + 85;//68;
            etiqueta->Alignment = taCenter;
            etiqueta->WordWrap = true;
            etiqueta->AutoSize = false;
            etiqueta->Transparent = true;
            etiqueta->Width = 81;
            etiqueta->Height = 33;
            etiqueta->Font->Name="Arial Narrow";
            etiqueta->Font->Size = 8;
            etiqueta->Tag = idx;
            etiqueta->Caption = pvp[idx].descr;

            this->InsertControl(etiqueta);

          }
        }
      }
   catch (...) {  // ENTER THIS BLOCK ONLY IF bad_alloc IS THROWN.
      // YOU COULD REQUEST OTHER ACTIONS BEFORE TERMINATING
      ShowMessage("Error, recursos insuficientes...");
      }



  lbHDescr->Caption="";
  lbHPVP->Caption="";
  DigitNum1->Value = 0;
  DigitNum2->Value = 0;
  /*
  screenerTV->Show();
  screenerTV->LetreroDigital1->FuenteRAW = fuenteLCD;
  */

}
//---------------------------------------------------------------------------
void __fastcall Tmain::SpeedButton1Click(TObject *Sender)
{
  TrackBar1->Position++;
}
//---------------------------------------------------------------------------
void __fastcall Tmain::SpeedButton2Click(TObject *Sender)
{
  TrackBar1->Position--;        
}
//---------------------------------------------------------------------------
void __fastcall Tmain::FormPaint(TObject *Sender)
{
  /* Texto rotado */
  Canvas->Font->Size = 36;                             //Font size
  Canvas->Font->Name = "Arial Black";                  //Font name
  LOGFONT lgfont;
  GetObject(Canvas->Font->Handle, sizeof(LOGFONT), &lgfont);
  lgfont.lfEscapement = 90*10;                         //Angle *10
  lgfont.lfOrientation = 90*10;                       //Angle *10
  lgfont.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  //Creates a logical font with the characteristics specified in the
  //LOGFONT structure
  Canvas->Font->Handle = CreateFontIndirect(&lgfont);
  SetGraphicsMode(Canvas->Handle, GM_ADVANCED);
  Canvas->Brush->Style = bsClear;                      //Draws transparently
  Canvas->Font->Color = 0x00CCE1E6;
  String text = "www.infdj.com";
  Canvas->TextOut(955,700, text);                       //Draws text
}
//---------------------------------------------------------------------------
void __fastcall Tmain::FormClose(TObject *Sender, TCloseAction &Action)
{
   int i,j;

   for (int j = 0; j < (filas*columnas);  j++)
   {
      delete productos[j];
      delete etiquetas[j];
   }

   delete[] etiquetas;                        // STEP 2: DELETE THE ROWS

   delete[] productos;                        // STEP 2: DELETE THE ROWS
   delete[] pvp;
}
//---------------------------------------------------------------------------
void __fastcall Tmain::MouseMove(TObject *Sender, TShiftState Shift,int X, int Y)
{
  producto = (TImage *)Sender;
  lbHDescr->Caption=pvp[producto->Tag].descr;
  lbHPVP->Caption=CurrToStrF(pvp[producto->Tag].PVPcurr, ffCurrency, 2);

  int t=pvp[producto->Tag].PVPcurr*100;
  DigitNum1->Value = t/100;
  DigitNum2->Value = t%100;


  if ( selector->Visible )
          muestraSelector(producto);

}
//---------------------------------------------------------------------------
void __fastcall Tmain::FormMouseMove(TObject *Sender, TShiftState Shift,
      int X, int Y)
{
  selector->Visible=false;
}
//---------------------------------------------------------------------------
void __fastcall Tmain::lbDescrDblClick(TObject *Sender)
{
  // Muestra el configurador para este elemento....
  prodConfig->setProd( producto->Tag,&pvp[producto->Tag] );
  prodConfig->ShowModal();

  producto->Picture->LoadFromFile(pvp[producto->Tag].imagen);
  etiquetas[producto->Tag]->Caption = pvp[producto->Tag].descr;
  
  muestraSelector(producto);
}
//---------------------------------------------------------------------------
void __fastcall Tmain::Click(TObject *Sender)
{
  producto = (TImage *)Sender;
  muestraSelector(producto);
}
//---------------------------------------------------------------------------
void __fastcall Tmain::muestraSelector(TImage *producto)
{
//  producto = (TImage *)Sender;
  lbDescr->Caption      = pvp[producto->Tag].descr;
  lbPVPmin->Caption     = pvp[producto->Tag].PVPmin;
  lbPVPmax->Caption     = pvp[producto->Tag].PVPmax;
  lbPVPcurr->Caption    = pvp[producto->Tag].PVPcurr;

  TrackBar1->Min        = 0;
  TrackBar1->Max        = pvp[producto->Tag].nclicks;
  TrackBar1->Position   = min(pvp[producto->Tag].clicks,pvp[producto->Tag].nclicks);

  lbClicks->Caption = AnsiString(TrackBar1->Position);
  

  selector->Left = min( Width - selector->Width - 10,  max( producto->Left+(producto->Width/2) - (selector->Width/2), 2));
  selector->Top  = producto->Top + (producto->Height/2) - selector->Height;
  selector->Visible=true;

  TrackBar1->SetFocus();
}
void __fastcall Tmain::TrackBar1Change(TObject *Sender)
{
  // Calculamos el nuevo precio actual...
  int d;
  Currency PVP;

  pvp[producto->Tag].clicks = TrackBar1->Position;
  lbClicks->Caption = AnsiString(TrackBar1->Position);
  PVP = (
            (pvp[producto->Tag].PVPmax - pvp[producto->Tag].PVPmin) / max(1,pvp[producto->Tag].nclicks)
        )
         * pvp[producto->Tag].clicks;

  // Redondeamos el precio según la primera cifra decimal...
//  PVP = pvp[producto->Tag].PVPmin + PVP/100;

  d = ((int)(PVP*100))%10;  // 1'64 -> 164%10 -> 4

  if ( d>5 )
  {
        d = ((int)(PVP*10))+1;      PVP = (Currency)d/10;
  } else {
        d = ((int)(PVP*10));        PVP = (Currency)d/10;
  }

  pvp[producto->Tag].PVPcurr = PVP + pvp[producto->Tag].PVPmin;

  lbPVPcurr->Caption    = pvp[producto->Tag].PVPcurr;
  lbHPVP->Caption       = CurrToStrF(pvp[producto->Tag].PVPcurr, ffCurrency, 2);

  int t=pvp[producto->Tag].PVPcurr*100;
  DigitNum1->Value = t/100;
  DigitNum2->Value = t%100;

  screenerTV->reOrdenar(pvp);
}
//---------------------------------------------------------------------------


void __fastcall Tmain::Button1Click(TObject *Sender)
{
  screenerTV->Left = TVx;
  screenerTV->Top = TVy;
  if ( TVm )
          screenerTV->WindowState=wsMaximized;
  screenerTV->Show();
  screenerTV->LetreroDigital1->FuenteRAW = fuenteLCD;
  screenerTV->LetreroDigital1->FrecReloj = 25;
  screenerTV->reOrdenar(pvp);
//  screenerTV->desordenAleatorio();
}
//---------------------------------------------------------------------------

void __fastcall Tmain::Edit1KeyPress(TObject *Sender, char &Key)
{
  if ( Key==VK_RETURN )
    screenerTV->LetreroDigital1->Letrero = Edit1->Text+"       ";      

}
//---------------------------------------------------------------------------

