//---------------------------------------------------------------------------
#include <io.h>
#include <vcl.h>
#pragma hdrstop

#include "TStatus.h"
#include "CtrlPPal.h"

#include "CtrlElemento.h"
#include "FichasClientes.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CoolForm"
#pragma link "DigitNum"
#pragma link "FormularioREUSABLE"
#pragma resource "*.dfm"
TStatus *Status;

#define Comienzo TbElementosCFG->FieldByName("Comienzo")->AsDateTime

#define pTiempo  TbElementosCFG->FieldByName("Tiempo")->AsDateTime
//---------------------------------------------------------------------------
__fastcall TStatus::TStatus(TComponent* Owner)
    : TFormREUSABLE(Owner)
{
 //     CtrlPPal->TbElementosCFG->FieldByName("NumElement")->AsString + " --";

 TbPrecios->Active = true;
 TbHistorial ->Active = true;
 TbElementosCFG->Active = true;

// TiempoPedido->DateTime = 0;
// TiempoPedido->Time = 0;

 ltime2Click( 0 );
}
//---------------------------------------------------------------------------
void __fastcall TStatus::SetElement( TElemento *Elto )
{
 Elemento = Elto;

 Terminal->Caption = "Terminal n�mero: -- " + AnsiString( Elemento->NumElemento ) + " --";

 if ( CtrlPPal->ServerHook ) return;

 if ( ! TbElementosCFG->Locate( "NumElement", Elemento->NumElemento, TLocateOptions() << loCaseInsensitive ) )
  ShowMessage( "ERROR, EL TERMINAL NO SE ENCONTRO!!\nAPPLICATION MALFUNTIONNNN Granted" );

// if ( ! TbElementosCFG->FieldByName( "Activo" )->AsBoolean )
 if ( Elemento->StatusCode == FREE )
 {
         MasTiempo->Visible = false;

   Label2->Caption = "&Tiempo que pide:";
   Label4->Caption = "&Tipo de Conexi�n:";
   PrecioAcumulado = 0; 
   ActivarTerminal->Visible = true;
   ActivarTerminal->Enabled = true;
   TipoConexion->Enabled = true;

//   TiempoPedido->Enabled = true;
        Edit1->Enabled = true;
        Edit2->Enabled = true;
        SetCliente->Enabled = true;
   TbElementosCFG->Edit();
   Comienzo = TDateTime::CurrentTime();
   TbElementosCFG->Post();
 } else {
   // El terminal est� ocupado
   unsigned short Hour, Min, Sec, MSec;
        Label4->Caption = AnsiString(PrecioAcumulado) + " acumuladas.";
        pTiempo.DecodeTime( &Hour, &Min, &Sec, &MSec );
        Edit1->Text = AnsiString( Hour );
        Edit2->Text = AnsiString( Min );
        Label3->Caption = Elemento->NCliente;
//   TiempoPedido->Time = pTiempo;
//   TiempoPedidoChange( 0 );
        MasTiempo->Visible = true;
 }
}
//---------------------------------------------------------------------------
void __fastcall TStatus::Time1MouseUp(TObject *Sender, TMouseButton Button,
      TShiftState Shift, int X, int Y)
{
 ltime1Click( Sender );
}
//---------------------------------------------------------------------------
void __fastcall TStatus::Time2MouseUp(TObject *Sender, TMouseButton Button,
      TShiftState Shift, int X, int Y)
{
 ltime2Click( Sender );
}
//---------------------------------------------------------------------------
void __fastcall TStatus::Time3MouseUp(TObject *Sender, TMouseButton Button,
      TShiftState Shift, int X, int Y)
{
 ltime3Click( Sender );
}
//---------------------------------------------------------------------------
void __fastcall TStatus::ltime1Click(TObject *Sender)
{
  unsigned short nullValue, h, m;
  Time1 -> Brush -> Color = clRed;
  Time2 -> Brush -> Color = clBlack;
  Time3 -> Brush -> Color = clBlack;

  Comienzo.DecodeTime( &h, &m, &nullValue, &nullValue );
  Dig1->Value = h;
  Dig2->Value = m;
}
//---------------------------------------------------------------------------
void __fastcall TStatus::ltime2Click(TObject *Sender)
{
  TDateTime lleva;  unsigned short nullValue, h, m;

  Time1 -> Brush -> Color = clBlack;
  Time2 -> Brush -> Color = clRed;
  Time3 -> Brush -> Color = clBlack;

  lleva = TDateTime::CurrentTime() - Comienzo;

  lleva.DecodeTime( &h, &m, &nullValue, &nullValue );
  Dig1->Value = h;
  Dig2->Value = m;
}
//---------------------------------------------------------------------------
void __fastcall TStatus::ltime3Click(TObject *Sender)
{
  TDateTime Queda;  unsigned short nullValue, h, m;

  Time1 -> Brush -> Color = clBlack;
  Time2 -> Brush -> Color = clBlack;
  Time3 -> Brush -> Color = clRed;

  Queda = ( pTiempo + Comienzo ) - TDateTime::CurrentTime();
  Queda.DecodeTime( &h, &m, &nullValue, &nullValue );
  Dig1->Value = h;
  Dig2->Value = m + 1;
}
//---------------------------------------------------------------------------
void __fastcall TStatus::ActivarTerminalClick(TObject *Sender)
{
  int HorasP = Edit1->Text.ToInt();
  int MinutP = Edit2->Text.ToInt();
  // Una vez asignado el terminal a una persona, ya no le puede ser reasignado
  // tiempo, ni puede cambiarse el usuario propietario de �l.

  // Abrimos la tabla de ventas de mi otro programa
  // Insertamos esto como venta: (Cliente | [TipoConexion+Tiempo] | 1und | PrecioConexionTotal)
  // Cerramos la tabla

  if ( HorasP == 0 && MinutP == 0 )
   return;

  // Comprobamos que no se le asigne mas tiempo del que dispone en el bono
  if ( idCliente > 0 && ClienteUsaBono &&
                        ( HorasP > TBonoH ||
                         (HorasP ==TBonoH && MinutP > TBonoM)
                        )
     )
  {
    ShowMessage ( "Atenci�n, al cliente: \n" + Label3->Caption + "\nsolo le quedan " + TBonoH +":"+TBonoM + " disponible.\nNo puedo asignar mas tiempo." );
    return;
  }


  // Desactivamos los controles...
  TipoConexion->Enabled = false;
//  TiempoPedido->Enabled = false;
        Edit1->Enabled = false;
        Edit2->Enabled = false;

  ActivarTerminal->Enabled = false;
  ActivarTerminal->Visible = false;

 if ( ! CtrlPPal->ServerHook )
 {
  // Activamos el terminal
  TbElementosCFG ->Edit();
   TbElementosCFG ->FieldByName( "Activo" )->AsBoolean = true;
   Comienzo   = TDateTime::CurrentTime();
    pTiempo = EncodeTime( HorasP, MinutP, 0, 0 );
  TbElementosCFG ->Post();
 }
  ltime2Click( 0 );

  int idtc;
  switch ( TipoConexion->ItemIndex )
  {
    // Internet
    case 0:        idtc = 0;        break;
    // Juegos
    case 1:        idtc = 1;        break;
    // Otros
    case 2:        idtc = 3;        break;
    // Otros
    case 3:        idtc = 2;        break;
    default:       idtc = 2;        break;
  }

  //////// ACTIVAMOS REALMENTE EL TERMINAL ///////////////////////////////////
  Currency PrecioConexion;
  if ( idCliente > 0 && ClienteUsaBono )
        PrecioConexion = -1;
  else
        PrecioConexion = TbPrecios->FieldByName("Precio")->AsCurrency;
  CtrlPPal->SetActiveTimeElement( Elemento, pTiempo, idCliente, idtc, PrecioConexion );
  PrecioAcumulado += PrecioConexion;
  Close();
}
//---------------------------------------------------------------------------
void __fastcall TStatus::TiempoPedidoChange(TObject *Sender)
{
  TDateTime TiempoPedido;
/*
  if ( TiempoPedido->Time > EncodeTime( 5, 0, 0, 0 ) )
    TiempoPedido->Time = EncodeTime( 5, 0, 0, 0 );
*/
  try {
  if ( Edit1->Text.ToInt() < 0 || Edit1->Text.ToInt() > 5 ) Edit1->Text = "0";
  } catch(...) {                                            Edit1->Text = "0";
                                                            Edit1->SelStart= 0;
                                                            Edit1->SelLength= 1;
  }
  try {
  if ( Edit2->Text.ToInt() < 0 || Edit2->Text.ToInt() >59 ) Edit2->Text = "0";
  } catch(...) {                                            Edit2->Text = "0";
                                                            Edit2->SelStart= 0;
                                                            Edit2->SelLength= 1;
  }
  TiempoPedido = EncodeTime( Edit1->Text.ToInt(), Edit2->Text.ToInt(), 0, 0 );

  // Buscamos en la tabla de precios, al 1� que tenga un tiempo superior o igual
  // al que nos pide el cliente...
  TbPrecios->First();
  while( !TbPrecios->Eof && TbPrecios->FieldByName("Tiempo")->AsDateTime < TiempoPedido )//->Time )
     TbPrecios->Next();

  // Actualizamos el precio
  int Number = (TbPrecios->FieldByName("Precio")->AsCurrency)*100;
  Precio->Value = Number / 100;
  PrecioDec->Value = Number % 100;


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


void __fastcall TStatus::TbPreciosBeforeOpen(TDataSet *DataSet)
{
   // Si la tabla no existe, la creamos
 if ( access( (TbPrecios -> TableName).c_str(), 0 ) != 0 )
 {
	 // Usamos la propiedad FielDefs para definir
	 // las columnas que contendr� la tabla
     TbPrecios -> FieldDefs -> Clear();

	 TbPrecios -> FieldDefs -> Add("Tiempo",      ftTime,  0, false );
	 TbPrecios -> FieldDefs -> Add("Precio",      ftCurrency,  0, false );

     TbPrecios -> IndexDefs -> Clear();
	 TbPrecios -> IndexDefs -> Add("Primary", "Tiempo", TIndexOptions() << ixPrimary << ixUnique );

	 // Creamos la base...
	 TbPrecios -> CreateTable();
 }
}
//---------------------------------------------------------------------------
void __fastcall TStatus::SetClienteClick(TObject *Sender)
{
 TFClientes *Ficha;
 ClienteUsaBono = false;

 Ficha = new TFClientes(this);
 if ( Ficha -> ShowModal() == mrOk )
 {
  idCliente  = CtrlPPal->TbPersonas->FieldByName("CodCliente1")->AsInteger;
  TBonoH = CtrlPPal->TbPersonas->FieldByName("TiempoH")->AsInteger;
  TBonoM = CtrlPPal->TbPersonas->FieldByName("TiempoM")->AsInteger;
  Label3->Caption = CtrlPPal->TbPersonas->FieldByName("Nombre")->AsString + " " + CtrlPPal->TbPersonas->FieldByName("Apellidos")->AsString;
  ClienteUsaBono =((TBonoH > 0) || (TBonoM > 0));
 } else {
  idCliente = 0;
  Label3->Caption = "Anonimo";
 }
 delete Ficha;

 if ( ClienteUsaBono )
 {
  Precio->Visible = false;
  PrecioDec->Visible = false;

  UBono1->Visible = true;
  UBono2->Caption = AnsiString(TBonoH) + " : " + AnsiString(TBonoM);
  UBono2->Visible = true;
   } else {
  Precio->Visible = true;
  PrecioDec->Visible = true;

  UBono1->Visible = false;
  UBono2->Visible = false;
 }
}
//---------------------------------------------------------------------------

void __fastcall TStatus::Button1Click(TObject *Sender)
{
   ModalResult = mrCancel;        
}
//---------------------------------------------------------------------------

void __fastcall TStatus::MasTiempoClick(TObject *Sender)
{
   MasTiempo->Visible = false;

   ActivarTerminal->Visible = true;
   ActivarTerminal->Enabled = true;
   TipoConexion->Enabled = true;
        Label2->Caption = "&Tiempo que a�ade:";
        Edit1->Enabled = true;
        Edit2->Enabled = true;
        SetCliente->Enabled = true;
   TbElementosCFG->Edit();
   Comienzo = TDateTime::CurrentTime();
   TbElementosCFG->Post(); //
}
//---------------------------------------------------------------------------