{ *******************************************************************************
  Title: T2Ti ERP
  Description: Ferramentas diversas da Software House

  The MIT License

  Copyright: Copyright (C) 2010 T2Ti.COM

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rightto use,
  copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the
  Software is furnished to do so, subject to the following
  conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  OTHER DEALINGS IN THE SOFTWARE.

  The author may be contacted at:
  t2ti.com@gmail.com</p>

  @author Albert Eije (T2Ti.COM)
  @version 1.0
  ******************************************************************************* }
unit UTools;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, ComCtrls, ToolWin, ActnMan, ActnCtrls, PlatformDefaultStyleActnCtrls,
  ActnList, ImgList, StdCtrls, Buttons, FileCtrl, JvDriveCtrls, JvExStdCtrls,
  JvListBox, JvCombobox, Grids, ShellApi, ExtCtrls, IniFiles, Biblioteca,
  JvBaseDlg, JvBrowseFolder, JvComponentBase, JvZlibMultiple, DBClient,
  LabeledCtrls, DB, WideStrings, DBXMySql, SqlExpr, FMTBcd, Provider,
  JclStringLists, DBGrids, DBXFirebird, System.ImageList, System.Actions;

type
  TFT2TiTools = class(TForm)
    PageControl1: TPageControl;
    TabSheetRES: TTabSheet;
    ActionManager1: TActionManager;
    ActionToolBar1: TActionToolBar;
    ImageListBotaoNormal: TImageList;
    ImageListBotaoDesabilitado: TImageList;
    ActionLocalizarFormularios: TAction;
    GroupBox1: TGroupBox;
    ListBoxFormularioLocalizado: TListBox;
    GroupBox2: TGroupBox;
    ListBoxFormularioIncluido: TListBox;
    SpeedButton1: TSpeedButton;
    SpeedButton2: TSpeedButton;
    SpeedButton3: TSpeedButton;
    SpeedButton4: TSpeedButton;
    JvDriveCombo: TJvDriveCombo;
    JvDirectoryListBox: TJvDirectoryListBox;
    ActionGerarArquivoRES: TAction;
    ActionSair: TAction;
    ActionGerarConexaoIni: TAction;
    TabSheetConexaoIni: TTabSheet;
    GroupBox3: TGroupBox;
    EditServidor: TLabeledEdit;
    EditPorta: TLabeledEdit;
    GroupBox4: TGroupBox;
    EditLogin: TLabeledEdit;
    EditSenha: TLabeledEdit;
    ActionToolBar2: TActionToolBar;
    ActionRecarregaArquivoIni: TAction;
    ActionToolBar3: TActionToolBar;
    EditLoginCriptografado: TLabeledEdit;
    EditSenhaCriptografada: TLabeledEdit;
    ActionCompactarArquivo: TAction;
    JvZlibMultiple: TJvZlibMultiple;
    ActionGerarResPadraoEmpresa: TAction;
    ActionSelecionarArquivoScript: TAction;
    OpenDialog1: TOpenDialog;
    ActionGerarScriptAlteracao: TAction;
    CDSScript: TClientDataSet;
    CDSBanco: TClientDataSet;
    SQLConnection: TSQLConnection;
    SQLQuery: TSQLQuery;
    DataSetProvider: TDataSetProvider;
    ActionGerarArquivoAtualizaBD: TAction;
    function PossuiAtributo(Attr, Val: Integer): Boolean;
    procedure ExibirConteudoPasta(Pasta: String);
    procedure ActionLocalizarFormulariosExecute(Sender: TObject);
    function PegarAnotacaoFormulario(Arquivo: String): String;
    procedure SpeedButton1Click(Sender: TObject);
    procedure SpeedButton3Click(Sender: TObject);
    procedure SpeedButton4Click(Sender: TObject);
    procedure SpeedButton2Click(Sender: TObject);
    procedure ActionGerarArquivoRESExecute(Sender: TObject);
    procedure ActionSairExecute(Sender: TObject);
    procedure CarregaArquivoConexaoIni;
    procedure FormCreate(Sender: TObject);
    procedure ActionGerarConexaoIniExecute(Sender: TObject);
    procedure ActionRecarregaArquivoIniExecute(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  FT2TiTools: TFT2TiTools;
  Contador: Integer;

implementation

{$R *.dfm}

{$REGION 'Infra'}
procedure TFT2TiTools.ActionSairExecute(Sender: TObject);
begin
  Close;
end;

procedure TFT2TiTools.FormCreate(Sender: TObject);
begin
  CarregaArquivoConexaoIni;
end;
{$ENDREGION}

{$REGION 'Arquivo RES'}
procedure TFT2TiTools.ActionLocalizarFormulariosExecute(Sender: TObject);
begin
  ExibirConteudoPasta(JvDirectoryListBox.Directory);
end;

procedure TFT2TiTools.ExibirConteudoPasta(Pasta: String);
var
  ResultadoBusca: TSearchRec;
  Ret: Integer;
  TempNome, Formulario: String;
begin
  Ret := FindFirst(Pasta + '\*.*', faAnyFile, ResultadoBusca);
  try
    while Ret = 0 do
    begin
      if PossuiAtributo(ResultadoBusca.Attr, faDirectory) then
      begin
        if (ResultadoBusca.Name <> '.') And (ResultadoBusca.Name <> '..') then
        begin
          TempNome := Pasta + '\' + ResultadoBusca.Name;
          ExibirConteudoPasta(TempNome);
        end;
      end
      else
      begin
        if AnsiPos(ExtractFileExt(ResultadoBusca.Name), '.pas') > 0 then
        begin
          if (AnsiPos('Controller', ResultadoBusca.Name) = 0) and (AnsiPos('UMenu', ResultadoBusca.Name) = 0) and (AnsiPos('UBase', ResultadoBusca.Name) = 0) and (AnsiPos('UDataModule', ResultadoBusca.Name) = 0) and (AnsiPos('UFiltro', ResultadoBusca.Name) = 0) and
            (AnsiPos('ULogin', ResultadoBusca.Name) = 0) and (AnsiPos('ULookup', ResultadoBusca.Name) = 0) and (AnsiPos('UPapel', ResultadoBusca.Name) = 0) and (AnsiPos('UTela', ResultadoBusca.Name) = 0) and (AnsiPos('UTelaCadastro', ResultadoBusca.Name) = 0) and
            (AnsiPos('UUsuario', ResultadoBusca.Name) = 0) and (AnsiPos('VO', ResultadoBusca.Name) = 0) then
          begin
            Formulario := Trim(PegarAnotacaoFormulario(Pasta + '\' + ResultadoBusca.Name));
            if Formulario <> '' then
            begin
              if ListBoxFormularioLocalizado.Items.IndexOf(Formulario) = -1 then
                ListBoxFormularioLocalizado.Items.Add(Formulario);
            end;
          end;
        end;
      end;
      //
      Ret := FindNext(ResultadoBusca);
    end;
  finally
    begin
      FindClose(ResultadoBusca);
    end;
  end;
end;

function TFT2TiTools.PossuiAtributo(Attr, Val: Integer): Boolean;
begin
  Result := Attr and Val = Val;
end;

function TFT2TiTools.PegarAnotacaoFormulario(Arquivo: String): String;
var
  f: TextFile;
  Linha: String;
  Achou: Boolean;
begin
  Achou := False;
  AssignFile(f, Arquivo);
  Reset(f);
  While not Eof(f) do
  begin
    Readln(f, Linha);
    if AnsiPos('[TFormDescription', Linha) > 0 then
    begin
      Result := Trim(Linha);
      Achou := True;
    end;
    if AnsiPos('class(', Linha) > 0 then
    begin
      if Achou then
        Result := Result + '[' + Trim(Linha) + ']'
      else
        Break;
    end;
  end;
  CloseFile(f);
end;

procedure TFT2TiTools.SpeedButton1Click(Sender: TObject);
begin
  ListBoxFormularioIncluido.Items := ListBoxFormularioLocalizado.Items;
end;

procedure TFT2TiTools.SpeedButton2Click(Sender: TObject);
begin
  ListBoxFormularioIncluido.Items.Add(ListBoxFormularioLocalizado.Items[ListBoxFormularioLocalizado.ItemIndex]);
end;

procedure TFT2TiTools.SpeedButton3Click(Sender: TObject);
begin
  ListBoxFormularioIncluido.Clear;
end;

procedure TFT2TiTools.SpeedButton4Click(Sender: TObject);
begin
  ListBoxFormularioIncluido.DeleteSelected;
end;

procedure TFT2TiTools.ActionGerarArquivoRESExecute(Sender: TObject);
var
  ConteudoRC: TStringList;
  Parametros: String;
begin
  // grava arquivo TXT com os dados dos formulários
  ListBoxFormularioIncluido.Items.SaveToFile(ExtractFilePath(Application.ExeName) + 'T2TiERP_Forms.txt');

  // grava arquivo .RC para gerar o .RES
  ConteudoRC := TStringList.Create;
  ConteudoRC.Add('T2TiERP_Forms TXTFILE "T2TiERP_Forms.txt"');
  ConteudoRC.SaveToFile(ExtractFilePath(Application.ExeName) + 'T2TiERP_Forms.RC');

  // cria o arquivo .RES
  Parametros := '/k brcc32 "' + ExtractFilePath(Application.ExeName) + 'T2TiERP_Forms.RC"';
  ShellExecute(Handle, 'open', 'cmd', PChar(Parametros), '', SW_HIDE);
end;
{$ENDREGION}

{$REGION 'Arquivo ConexaoIni'}
procedure TFT2TiTools.CarregaArquivoConexaoIni;
var
  ConexaoIni: TIniFile;
begin
  try
    try
      ConexaoIni := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'Conexao.ini');

      with ConexaoIni do
      begin
        if not SectionExists('ServidorApp') then
        begin
          WriteString('ServidorApp', 'Servidor', 'localhost');
          WriteInteger('ServidorApp', 'Porta', 8080);
        end;
        if not SectionExists('Adm') then
        begin
          WriteString('Adm', 'Login', '');
          WriteString('Adm', 'Senha', '');
        end;

        EditServidor.Text := ReadString('ServidorApp', 'Servidor', '');
        EditPorta.Text := ReadString('ServidorApp', 'Porta', '');

        EditLogin.Text := Codifica('D',trim(ReadString('Adm', 'Login', '')));
        EditSenha.Text := Codifica('D',trim(ReadString('Adm', 'Senha', '')));
        EditLoginCriptografado.Text := ReadString('Adm', 'Login', '');
        EditSenhaCriptografada.Text := ReadString('Adm', 'Senha', '');
      end;
    except
      Application.MessageBox('Problemas ao carregar o arquivo Conexao.ini.', 'Informação do Sistema', MB_OK + MB_ICONERROR);
    end;
  finally
    ConexaoIni.Free;
  end;
end;

procedure TFT2TiTools.ActionGerarConexaoIniExecute(Sender: TObject);
var
  ConexaoIni: TIniFile;
begin
  try
    try
      ConexaoIni := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'Conexao.ini');

      with ConexaoIni do
      begin
        WriteString('ServidorApp', 'Servidor', 'localhost');
        WriteInteger('ServidorApp', 'Porta', 8080);
        WriteString('Adm', 'Login', Codifica('C', EditLogin.Text));
        WriteString('Adm', 'Senha', Codifica('C', EditSenha.Text));
      end;
    except
      Application.MessageBox('Problemas ao carregar o arquivo Conexao.ini.', 'Informação do Sistema', MB_OK + MB_ICONERROR);
    end;
  finally
    ConexaoIni.Free;
  end;
end;

procedure TFT2TiTools.ActionRecarregaArquivoIniExecute(Sender: TObject);
begin
  CarregaArquivoConexaoIni;
end;
{$ENDREGION}

end.


