#include <surround.h>
#include "freecheckgui.h"
#include "freecheckmain.h"
#include "freecheckextern.h"

#include <fcntl.h>
#include <exec/memory.h>
#include <proto/muimaster.h>
#include <clib/alib_protos.h>
#include <clib/dos_protos.h>
#include <clib/exec_protos.h>
#include <libraries/mui.h>
#include <libraries/asl.h>

/* VARIAVEIS GLOBAIS DE CONFIGURACAO */
char regname[100], regmail[100], regnumber[256], regcountry[100], 
     databasename[256], precision[10], regnumberreal[256], regorg[256],
     categorydefault[256], pricedefault[10], categorydir[256], moedac[10],
     nomemoeda[100], pilha[50][50];
int pilhafim = 0;

CarregaPilhaCategorias(char categoria[256])
{
  /* CARREGA OS LIMITES PARA UMA VARIAVEL GLOBAL */
  char a, teste[256];
  int x = 0, pos = 0;
  FILE *entrada;

  if(!(entrada = fopen(categoria, "r")))
    return 0;

  x = 0; pos = 0;
  while(a = getc(entrada), ! feof(entrada))
  {
    teste[x++] = a;
    if(a == '\n') {
      teste[--x] = '\0';
      strcpy(pilha[pos++], teste);
      teste[0] = '\0'; x = 0; }
  }
  pilhafim = --pos;
  fclose(entrada);
}

char *CalculaPrecoFREE(char arquivo[256], int hora1, int hora2, int semana, int pilhadim)
{
  /* Este comando calcula o preco de uma determinada ligacao.

  Entrada : Arquivo da Categoria   --> Categories/Brazil.CRT (CHAR 256)
            Hora Inicio (Segundos) --> 233445 (INT)
            Hora Final  (Segundos) --> 255455 (INT)
            Semana                 --> 0      (INT)
  Obs     : A semana eh recebida de acordo com os valores da funcao
            DiaSemana("01.02.1997", 2);
  Saida   : O custo da ligacao     --> 0.234  (CHAR 256)
            CalculaPrecoFREE("Categories/Brazil.CRT", 233445, 255455, 0);
  */

  char teste[256];
  int x = 0, fim = 0, h1 = 0, h2 = 0, h3 =0;
  float valor = 0, hvalor = 0, hvalorpadrao = 0, diferenca = 0, hhh = 0;

  hvalorpadrao = atof(pricedefault);

  /* FILTRA OS HORARIOS CASO TROQUE O DIA */
  if(hora2 < hora1)
  {
    diferenca = hora2;
    hora2 = 86399;
  }

  /* CASE PARA ACERTAR O DIA DA SEMANA DE ACORDO COM O COMBO */
  switch (semana)
  {
    case  0: semana = 6; break;
    case  1: semana = 7; break;
    case  2: semana = 1; break;
    case  3: semana = 2; break;
    case  4: semana = 3; break;
    case  5: semana = 4; break;
    case  6: semana = 5; break;
  }

  /* PILHA ONDE SERAO ARMAZENADOS LIMITES (pilha) MAXIMO 50 LIMITES
  A VARIAVEL QUE GUARDA O NUMERO DE LIMITES NA PILHA EH (xpilha) */

  LOOP:
  for(x = 0; x < pilhafim; x++)
  {
    strcpy(teste, pilha[x]);

    h1 = atoi(Corta(teste, ' ', 0));
    h2 = atoi(Corta(teste, ' ', 1));
    h3 = atoi(Corta(teste, ' ', 3));
    hvalor = atof(Corta(teste, ' ', 2));

    if(h3 == 0 || h3 == semana)
    {
      /* 5, 10 SELECIONADO (6, 9) ou (5, 10) ou (5, 9) ou (6, 10) */
      if((hora1 >= h1 && hora1 < h2) &&
         (hora2 <= h2 && hora2 > h1)) {
        hhh = hora2 - hora1;
        valor = valor + ((hhh / 60) * hvalor); fim = 1; break; }

      /* 5, 10 SELECIONADO (4, 9) ou (4, 10) */
      if((hora1 < h1 && hora1 < h2) &&
         (hora2 <= h2 && hora2 > h1)) {
        hhh = hora2 - h1;
        valor = valor + ((hhh  / 60) * hvalor);
        hora2 = h1; x = -1; }

      /* 5, 10 SELECIONADO (5, 11) ou (6, 11) */
      /* 5, 10 SELECIONADO (4, 11) */
      if(((hora1 >= h1 && hora1 < h2) &&
          (hora2 > h2 && hora2 > h1)) ||
         ((hora1 < h1 && hora1 < h2) &&
          (hora2 > h2 && hora2 > h1))) {
        hhh = h2 - hora1;
        valor = valor + ((hhh / 60) * hvalor);
        hora1 = h2; x = -1; }
    }
  }
  if(diferenca > 0)
  {
    hora1 = 0;
    hora2 = diferenca;
    diferenca = 0;
    goto LOOP;
  }
  if(fim == 0)
  {
    hhh = hora2 - hora1;
    valor = valor + ((hhh / 60) * hvalorpadrao);
  }
  sprintf(teste, "%f", valor);
  return teste;
}

char *TMsg(struct Hook *objeto)
{
  /* LE O CONTEUDO DE UM OBJETO, O TEXT */
  char *teste;
  get(objeto, MUIA_Text_Contents, &teste);
  return teste;
}

int MsgRegistro(void)
{
  MUI_Request(App->App, 0, 0, 0, TMsg(App->Msg02), TMsg(App->Msg01));
  return NULL;
}

APTR CarregaUpdate( struct Hook *a0, APTR a2, APTR a1 )
{
  char senha1[256], senha2[256], senhatmp[256], categoria[256],
       campo[256], cost[30],
       diferenca[256], horaon[30], dataon[30], tempoon[30],
       teste[256], l1[256], connect[256], telefone[30];
  int registro = 0;

  /* TESTA SE O DIRETORIO DA BASE DE DADOS EXISTE */
  if(!ExisteDiretorio(databasename) || !strcmp(databasename, ""))
  {
    DoMethod(App->JanelaPrincipal, MUIA_Window_Open, FALSE);
    MUI_Request(App->App, 0, 0, 0, TMsg(App->Msg02), TMsg(App->Msg03));
    DoMethod(App->App, MUIM_Application_ReturnID, MUIV_Application_ReturnID_Quit);
    return NULL;
  }

  /* ROTINA QUE TESTA O TIPO DE REGISTRO
     VARIAVEIS A DEFINIR */
  strcpy(senha1, AsciiString(regnumber, 69));
  strcpy(senha2, AsciiString(regnumberreal, 96));
  sprintf(senhatmp, "%s%s%s", regname, regmail, regcountry);
  strcpy(senhatmp, CriptografiaSimples(senhatmp, 0));
  if(!strcmp(senha1, senhatmp))
    registro = 1;
  if(!strcmp(senha1, senhatmp) && !strcmp(senha2, senhatmp))
    registro = 2;
  if(!strcmp(regnumber, ""))
    registro = 0;
  
  /* TESTA SE O REGISTRO EH NO MINIMO NOPAY */
  if(registro == 0)
  {
    DoMethod(App->JanelaPrincipal, MUIA_Window_Open, FALSE);
    MsgRegistro();
    DoMethod(App->App, MUIM_Application_ReturnID, MUIV_Application_ReturnID_Quit);
    return NULL;
  }

  /* Rotina que limpa os campos antes da atribuicao */
  set(App->LabelConnect, MUIA_Text_Contents, "");
  set(App->LabelOnline, MUIA_Text_Contents, "");
  set(App->LabelCost, MUIA_Text_Contents, "");
  set(App->LabelStatusCall, MUIA_Text_Contents, "");

  sprintf(categoria, "%s/%s", categorydir, categorydefault);

  /* ROTINA QUE CARREGA O STATUS DA LIGACAO ATUAL */
  if(!Conectado()) {
    /* NOT CONNECTED... */
    set(App->LabelConnect, MUIA_Text_Contents, TMsg(App->Msg06));
    set(App->LabelOnline, MUIA_Text_Contents, TMsg(App->Msg06));
    set(App->LabelCost, MUIA_Text_Contents, TMsg(App->Msg06));
    set(App->LabelStatusCall, MUIA_Text_Contents, TMsg(App->Msg04));
    return NULL; }

  if(!ExisteArquivo("S:Freedom.Miami.Temp")) {
    /* FREEEVENTMIAMI LOG NOT FOUND */
    set(App->LabelConnect, MUIA_Text_Contents, TMsg(App->Msg06));
    set(App->LabelOnline, MUIA_Text_Contents, TMsg(App->Msg06));
    set(App->LabelCost, MUIA_Text_Contents, TMsg(App->Msg06));
    set(App->LabelStatusCall, MUIA_Text_Contents, TMsg(App->Msg05));
    return NULL; }

  strcpy(campo, LeRegistroDB("s:Freedom.Miami.Temp", "1"));
  strcpy(horaon, Corta(campo, ',', 2));
  strcpy(dataon, Corta(campo, ',', 1));
  strcpy(telefone, Corta(campo, ',', 0));
  strcpy(connect, Corta(campo, ',', 3));
  if(!strcmp(connect, "CUTERRO"))
    strcpy(connect, "");

  /* CONNECT */
  sprintf(teste, "%s %s", dataon, SegundoHora(horaon));
  set(App->LabelConnect, MUIA_Text_Contents, teste);

  strcpy(tempoon, IntervaloHora(horaon, HoraSegundo(DataHora(5))));

  /* VERIFICA SE PASSOU DA MEIA NOITE A LIGACAO ATUAL */
  strcpy(diferenca, Corta(DiferencaDias(dataon, DataHora(0)), ':', 1));
  if(atoi(diferenca) > 0)
    sprintf(tempoon, "%ld", atoi(diferenca) - atoi(tempoon));

  /* CALCULA O CUSTO DA LIGACAO */
  strcpy(l1, CalculaPrecoFREE(categoria, atoi(horaon), atoi(HoraSegundo(DataHora(5))), atoi(DiaSemana(DataHora(0), 2)), pilhafim));
  strcpy(l1, CasasAposCaracter(l1, '.', atoi(precision)));
  if(atoi(moedac) == 0)
    sprintf(cost, "%s%s", nomemoeda, l1);
  else
    sprintf(cost, "%s%s", l1, nomemoeda);
  if(registro < 2)
    strcpy(cost, "REALREG");

  /* ONLINE */
  sprintf(teste, "\033b%s\033n", SegundoHora(tempoon));
  set(App->LabelOnline, MUIA_Text_Contents, teste);

  /* COST */
  sprintf(teste, "%s", cost);
  set(App->LabelCost, MUIA_Text_Contents, teste);

  /* STATUS */
  sprintf(teste, "\0338%s\n%s\033n", telefone, connect);
  set(App->LabelStatusCall, MUIA_Text_Contents, teste);
  
  return NULL;
}

APTR CarregaConfig( struct Hook *a0, APTR a2, APTR a1 )
{
  char categoria[256], teste[256], var[256];

  /* TESTA SE EXISTE O ASSIGN PARA ENCONTRAR O CONFIG */
  if(!(ExisteDiretorio("Freedom:")))
  {
    /* FREEDOM NEEDS ASSIGN */
    DoMethod(App->JanelaPrincipal, MUIA_Window_Open, FALSE);
    MUI_Request(App->App, 0, 0, 0, TMsg(App->Msg02), TMsg(App->Msg07));
    DoMethod(App->App, MUIM_Application_ReturnID, MUIV_Application_ReturnID_Quit);
    return NULL;
  }

  strcpy(regname, LeRegistroDB("Freedom:Freedom.Config", "regname"));
  strcpy(regmail, LeRegistroDB("Freedom:Freedom.Config", "regemail"));
  strcpy(regnumber, LeRegistroDB("Freedom:Freedom.Config", "regnumber"));
  strcpy(regorg, LeRegistroDB("Freedom:Freedom.Config", "regorganiz"));
  strcpy(regcountry, LeRegistroDB("Freedom:Freedom.Config", "regcountry"));
  strcpy(databasename, LeRegistroDB("Freedom:Freedom.Config", "databasename"));
  strcpy(categorydefault, LeRegistroDB("Freedom:Freedom.Config", "categorydefault"));
  strcpy(pricedefault, LeRegistroDB("Freedom:Freedom.Config", "pricedefault"));
  strcpy(categorydir, LeRegistroDB("Freedom:Freedom.Config", "categorydir"));
  strcpy(precision, LeRegistroDB("Freedom:Freedom.Config", "precision"));
  strcpy(regnumberreal, LeRegistroDB("Freedom:Freedom.Config", "regnumberreal"));

  /* CARREGA INFORMACOES DA MOEDA */
  sprintf(categoria, "%s/%s", categorydir, categorydefault);
  CarregaPilhaCategorias(categoria);
  sprintf(teste, LeRegistroDB(categoria, "money"));

  strcpy(var, Corta(teste, '@', 1));
  if(!strcmp(var, "CUTERRO"))
    strcpy(nomemoeda, "");
  else
    strcpy(nomemoeda, var);
  strcpy(moedac, Corta(teste, '@', 0));

  return NULL;
}

APTR AcertaAbout( struct Hook *a0, APTR a2, APTR a1 )
{
  /* ATUALIZA INFORMACOES JANELA ABOUT, SOBRE O TIPO DE REGISTRO */
  char reg[256], org[256], teste[256], senha1[256], senha2[256],
       senhatmp[256];
  int registro = 0;

  if(!strcmp(TrimSur(regorg, 0), ""))
    sprintf(org, "(%s)", regcountry);
  else
    sprintf(org, "(%s - %s)", regcountry, regorg);

  /* ROTINA QUE TESTA O TIPO DE REGISTRO 
     VARIAVEIS A DEFINIR
   char senha1[256], senha2[256], senhatmp[256], *regnumber2,
        *regemail, *regnumber, *regname, *regorg, *regcountry;
   int registro = 0;
  */
  strcpy(senha1, AsciiString(regnumber, 69));
  strcpy(senha2, AsciiString(regnumberreal, 96));
  sprintf(senhatmp, "%s%s%s", regname, regmail, regcountry);
  strcpy(senhatmp, CriptografiaSimples(senhatmp, 0));
  if(!strcmp(senha1, senhatmp))
    registro = 1;
  if(!strcmp(senha1, senhatmp) && !strcmp(senha2, senhatmp))
    registro = 2;
  if(!strcmp(regnumber, ""))
    registro = 0;

  if(registro == 0)
    strcpy(reg, "\033bUNREGISTERED\033n\nRegister is a free e-mail!");
  if(registro == 1)
      sprintf(reg, "\033bNOPAY REGISTERED\033n\n%s\n%s", regname, org);
  if(registro == 2)
      sprintf(reg, "\033bREAL REGISTERED\033n\n%s\n%s", regname, org);

  sprintf(teste, "\033c\0338\033b\nFreedom Module (Explore Call)\nVersion 1.02 [24/02/2000]\033n\nBy Cristian Robert Gallas\n\nSuRRouND on IRC [Made in Brazil 97-00]\n\nEmail for bug reports: surround@iname.com\n [members.tripod.com/surround_br] \n\nThis version is:\n%s\n", reg);
  set(App->TextAbout, MUIA_Text_Contents, teste);
  return NULL;
}

APTR AplicacaoHide( struct Hook *a0, APTR a2, APTR a1 )
{ 
  /* MINIMIZA A APLICACAO, COLOCA ELA EM ICONIFIED */
  set(App->App, MUIA_Application_Iconified, TRUE);
  return NULL;
}

APTR AboutMUI( struct Hook *a0, APTR a2, APTR a1 )
{
  DoMethod(App->App, MUIM_Application_AboutMUI, App->JanelaPrincipal);
  return NULL;
}

APTR CarregaTempo( struct Hook *a0, APTR a2, APTR a1 )
{

  return NULL;
}
