//---------------------------------------------------------------------------
#include <inifiles.hpp>

#include <vcl.h>
#pragma hdrstop

#include "MultiBase_PRJ.h"
#include "AcercaDe.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CoolForm"
#pragma link "CoolForm"
#pragma link "CoolForm"
#pragma link "AdvGrid"
#pragma resource "*.dfm"
TMultiBase *MultiBase;
//---------------------------------------------------------------------------
__fastcall TMultiBase::TMultiBase(TComponent* Owner)
        : TForm(Owner)
{
  filtrando = false;
  modificado = false;
  StatusBar1->Panels->Items[0]->Text = "Inicializando programa...";
  LoadData("Peliculas.ini");
  VisibilidadColumnas();
  StatusBar1->Panels->Items[0]->Text = "";
}
//---------------------------------------------------------------------------
void __fastcall TMultiBase::McolumnasClick(TObject *Sender)
{
    TMenuItem *ClickedItem = dynamic_cast<TMenuItem *>(Sender);
    if (ClickedItem)
    {
        ClickedItem->Checked = !ClickedItem->Checked;
        if ( ClickedItem->Checked )
           Visualizador->UnhideColumn(ClickedItem->Tag);
        else
           Visualizador->HideColumn(ClickedItem->Tag);

        Visualizador->AutoSize = true;
    }
}
//---------------------------------------------------------------------------
void __fastcall TMultiBase::VisibilidadColumnas(void)
{
 TMenuItem * MenuItem;
 for (int i=2; i<Mcolumnas->Items->Count; i++)
 {
  MenuItem = Mcolumnas->Items->Items[i];
  if ( MenuItem->Checked )
   Visualizador->UnhideColumn(MenuItem->Tag);
  else
   Visualizador->HideColumn(MenuItem->Tag);
 }
 Visualizador->AutoSize = true;
}
//---------------------------------------------------------------------------
void __fastcall TMultiBase::LoadData(AnsiString File)
{
 TMenuItem *NewItem, *SubNewItem;
 AnsiString Genero, Registro, LUp, LUpZ;
 int i, j;

 TIniFile *ini;
 ini = new TIniFile( ExtractFileDir( Application->ExeName ) + "\\Peliculas.INI" );

 delimitador = ini->ReadString( "CFG", "delimitador", "·" );

 // **************************************************************************** RegAnt = 0; RegSig = 0;
 StatusBar1->Panels->Items[0]->Text = "Recuperando estructura";

 Registro  = ini->ReadString( "zIndex", "n0", "" );
 if ( !Registro.IsEmpty() )
 {
  Visualizador->ColCount = 2 + Analiza( Registro );
  columnas =  Visualizador->ColCount;
  Visualizador->HideColumn(Visualizador->ColCount-1);
  LookUp = new TStringList *[ Visualizador->ColCount ];
  for ( i=0; i<Visualizador->ColCount; i++ )
    LookUp[i] = 0;
         // ****************************************************************************
         StatusBar1->Panels->Items[0]->Text = "Cargando LookUp's";
         AnsiString LookUpC; int PosDel;
         luTable = new LookUpTable[Visualizador->ColCount];
         for ( i=0; i< (Visualizador->ColCount-2) ;i++)
         {
          LookUpC = ini->ReadString( "LookUp", "n"+AnsiString(i), "" );
          if ( LookUpC.IsEmpty() ) break;
          PosDel = LookUpC.Pos( delimitador );
          luTable[i].Columna = ( LookUpC.SubString( 1, PosDel-1 ) ).ToInt();
          luTable[i].Clave = LookUpC.SubString( PosDel+1, LookUpC.Length() - PosDel );
          StatusBar1->Panels->Items[0]->Text = "Analizando LookUp: " + luTable[i].Clave;
                //************************************
                /*  M    */NewItem = new TMenuItem(Mfiltros);
                /*  E  F */NewItem->Caption = luTable[i].Clave;
                /*  N  i */NewItem->Tag = luTable[i].Columna;
                /*  Ú  l *///NewItem->GroupIndex = 1;
                /*     t *///NewItem->Checked = false;
                /*  d  r *///NewItem->RadioItem = true;
                /*  e  o *///NewItem->OnClick = SeleccionDeFiltroClick;
                /*     s */Mfiltros->Items->Add(NewItem);
                //************************************
                LookUp[luTable[i].Columna] = new TStringList();
                LUpZ = luTable[i].Clave[1];
                LUpZ = LUpZ.LowerCase();
                for ( j=0; ;j++ )
                {
                 LUp = ini->ReadString( luTable[i].Clave, LUpZ+AnsiString(j), "" );
                 if ( LUp.IsEmpty() )
                   break;
                 ( LookUp[ luTable[i].Columna ] )->Add( LUp );
                        //************************************
                        /*  S    */SubNewItem = new TMenuItem(NewItem);
                        /*  U  F */SubNewItem->Caption = LUp;
                        /*  B  i */SubNewItem->Tag = luTable[i].Columna;
                        /*  M  l */SubNewItem->GroupIndex = 1;
                        /*  E  t */SubNewItem->Checked = false;
                        /*  N  r */SubNewItem->RadioItem = true;
                        /*  Ú  o */SubNewItem->OnClick = SeleccionDeFiltroClick;
                        /*     s */NewItem->Add(SubNewItem);
                        //************************************
                }
                //************************************
         }
         anyLookUp = (i>0);
         LookABLEcolumns = i;
         // **************************************************************************** RegAnt = 0; RegSig = 0;

  Almacena( Registro, 0, ini );
  Visualizador->RowCount = 3;

  StatusBar1->Panels->Items[0]->Text = "Recuperando registros";
  for (i=1; ;i++)
  {
   Registro = ini->ReadString( "zIndex", "n"+AnsiString( i ), "" );
   if ( Registro.IsEmpty() ) break;
   Almacena( Registro, i, ini );
   Visualizador->RowCount = i + 2;
  }
  Visualizador->RowCount--;

  RegAnt = i-1;
  RegSig = i;
 } else {
  ShowMessage( "La Estructura inicial NO EXISTE :_(" );
 }
 // ****************************************************************************
 StatusBar1->Panels->Items[0]->Text = "";

 delete ini;
}
//---------------------------------------------------------------------------
int __fastcall TMultiBase::Analiza( AnsiString Registro )
{
  int dev=1, i=1;
  while ( i < Registro.Length() )
  {
    if ( Registro[i] == delimitador[1] )    dev ++;
    i++;
  }
  return dev;
}
//---------------------------------------------------------------------------
int __fastcall TMultiBase::Almacena( AnsiString Registro, int Numero, TIniFile *ini )
{
  TMenuItem *NewItem;
  int cols=1, PosDel, j;
  AnsiString ValorCampo;

  Visualizador->Cells[0][Numero] = AnsiString( Numero );

  while ( cols < Visualizador->ColCount )
  {
   PosDel = Registro.Pos( delimitador );
   if ( LookABLEcolumns > 0 )
   {
     for ( j=0; j<LookABLEcolumns; j++ )
     {
      if ( luTable[j].Columna == cols )
      {
       if ( PosDel == 0 )
          ValorCampo = ini->ReadString( luTable[j].Clave, Registro, Registro );
       else
          ValorCampo = ini->ReadString( luTable[j].Clave, Registro.SubString( 1, PosDel-1 ), Registro.SubString( 1, PosDel-1 ) );
       break;
      }
     }
   }

   if ( LookABLEcolumns <= 0 || j >= LookABLEcolumns )
   {
    if ( PosDel == 0 )
      ValorCampo = Registro;
    else
      ValorCampo = Registro.SubString( 1, PosDel-1 );
   }

   Visualizador->Cells[cols][Numero] = ValorCampo;

   Registro = Registro.SubString( PosDel+1, Registro.Length() - PosDel );

   if ( Numero == 0 )
   {
      NewItem = new TMenuItem(Mcolumnas);
      NewItem->Caption = ValorCampo;
      NewItem->Tag = cols;
      ValorCampo = ini->ReadString( "CFG", "columnas", "" );
      if ( ValorCampo.IsEmpty() || cols > ValorCampo.Length() )
        NewItem->Checked = true;
      else
        NewItem->Checked = (ValorCampo[ cols ]=='0') ? false : true;
      NewItem->OnClick = McolumnasClick;
      Mcolumnas->Items->Add(NewItem);
   }
   cols++;
  }

  return 0;
}
//---------------------------------------------------------------------------
bool __fastcall TMultiBase::GuardarCambios(void)
{
 AnsiString Cambio;
 int i;
 // GuardarCambios

 // Hacemos visibles todas las columnas...
/*
 for ( i=0; i<columnas; i++ )
  Visualizador->UnhideColumn(i);
*/
 filtrando = true;
 Visualizador->UnhideColumn(columnas-1);
 // Filtramos para ver que ha cambiado...
 TFilterData* fd;
 Visualizador->FilterActive = false;
 Visualizador->Filter->Clear();
 fd = Visualizador->Filter->Add();
 fd->Condition = "M";
 fd->Column = (columnas-1);
 Visualizador->FilterActive = true;
 filtrando = false;
/*
 // Recorremos todas las filas
 for ( int j=1; j < Visualizador->RowCount; j++ )
 {
   i = 0;
   Cambio = CompactaTexto( i, (Visualizador->Rows[j])->Strings[j] );
   // y todas las columnas
   for ( i=1; i<columnas; i++ )
     // Anexamos las columnas teniendo en cuenta los LookUps
     Cambio += delimitador + CompactaTexto( i, (Visualizador->Rows[j])->Strings[i] );

   // Guardamos la fila cambiada
   ShowMessage( Cambio );
 }
*/
 return true;
}
//---------------------------------------------------------------------------
AnsiString __fastcall TMultiBase::CompactaTexto( int Columna, AnsiString Texto )
{
 AnsiString dev;
 dev = Texto;
 // Si existen columnas LookABLES
 if ( LookABLEcolumns > 0 )
 {
     // Recorremos la tabla de LookUps
     for ( int j=0; j<LookABLEcolumns; j++ )
     {
      // Si esta columna ES LookABLE
      if ( luTable[j].Columna == Columna )
      {
       // Realizamos un LookUps INVERSO
       /*
       ValorCampo = ini->ReadString( luTable[j].Clave, Registro, Registro );
       */
       break;
      }
     }
 }

 return dev;
}
//---------------------------------------------------------------------------
void __fastcall TMultiBase::FormClose(TObject *Sender,
      TCloseAction &Action)
{
 AnsiString Message = "Se han producido algunos cambios. ¿Deseea guardar los cambios?";

 while ( modificado )
 {
  if ( MessageDlg( Message, mtConfirmation, TMsgDlgButtons() << mbYes << mbNo, 0) == mrYes)
  {
    if ( GuardarCambios() )
      modificado = false;
    else
      Message = "Los cambios no pudieron ser guardados. ¿Volver a intentar?";
  } else
    modificado = false;
 }


 for ( int i=0; i<Visualizador->ColCount; i++ )
  if ( LookUp[i] )
          delete LookUp[i];
 delete [] LookUp;

 delete [] luTable;
}
//---------------------------------------------------------------------------
void __fastcall TMultiBase::SpeedButton1Click(TObject *Sender)
{
 Close();        
}
//---------------------------------------------------------------------------




void __fastcall TMultiBase::SpeedButton2Click(TObject *Sender)
{
  TAboutBox *About;
  About = new TAboutBox( this );
  About->ShowModal();
  delete About;
}
//---------------------------------------------------------------------------



void __fastcall TMultiBase::bColumnasClick(TObject *Sender)
{
 Mcolumnas->Popup(Left + bColumnas->Left, Top + bColumnas->Top);        
}
//---------------------------------------------------------------------------

void __fastcall TMultiBase::VisualizadorGetEditorType(TObject *Sender,
      int ACol, int ARow, TEditorType &aEditor)
{
  if ( LookUp[ACol] && LookUp[ACol]->Count > 0 )
  {
    Visualizador->ClearComboString();
    for ( int i=0; i < LookUp[ACol]->Count; i++ )
      Visualizador->AddComboString( LookUp[ACol]->Strings[i] );
    Visualizador->Combobox->Sorted=false;

    aEditor=edComboList;
  }
}
//---------------------------------------------------------------------------
void __fastcall TMultiBase::VisualizadorCellsChanged(TObject *Sender,
      TRect &R)
{
 if ( !filtrando )
 {
   (Visualizador->Rows[Visualizador->Row])->Strings[columnas-1] = "M";
   modificado = true;
 }
}
//---------------------------------------------------------------------------


void __fastcall TMultiBase::bFiltrosClick(TObject *Sender)
{
 Mfiltros->Popup(Left + bFiltros->Left, Top + bFiltros->Top);
}
//---------------------------------------------------------------------------

void __fastcall TMultiBase::SeleccionDeFiltroClick(TObject *Sender)
{
 TFilterData* fd;
 AnsiString Condicion; int i;
 TMenuItem *ClickedItem = dynamic_cast<TMenuItem *>(Sender);

 filtrando = true;
 // Ajustamos el nuevo filtro
 Visualizador->FilterActive = false;
 if ( ClickedItem->Tag > 0 )
 {
   Visualizador->FilterActive = false;
   Visualizador->Filter->Clear();
   fd = Visualizador->Filter->Add();
   for ( i=1; i<=ClickedItem->Caption.Length(); i++ )
     if ( (ClickedItem->Caption)[i] != '&' )
           Condicion += (ClickedItem->Caption)[i];
   fd->Condition = Condicion;
   fd->Column = ClickedItem->Tag;
   Visualizador->FilterActive = true;

   if ( ClickedItem->Tag > 0 )
        ClickedItem->Checked = true;
 }
 Visualizador->AutoSize = true;

 filtrando = false;
}
//---------------------------------------------------------------------------

void __fastcall TMultiBase::SpeedButton3Click(TObject *Sender)
{
 GuardarCambios();        
}
//---------------------------------------------------------------------------

