//---------------------------------------------------------------------------
#include <vcl.h>
#include <IniFiles.hpp>
#include <stdio.h>
#pragma hdrstop
#include "FrmTikers.h"
#include "frmConfig.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TFormTikers *FormTikers;
//---------------------------------------------------------------------------
__fastcall TFormTikers::TFormTikers(TComponent* Owner):TForm(Owner)
{
   IdHTTP1->Request->AcceptCharSet = "iso-8859-1,*,utf-8";
   IdHTTP1->Request->AcceptLanguage = "ru,en-us,en";
   IdHTTP1->HTTPOptions << hoForceEncodeParams;

   if( ProxyEnable )
   {
	  IdHTTP1->ProxyParams->ProxyServer   = ProxyServer;
	  IdHTTP1->ProxyParams->ProxyPort	  = ProxyPort;
	  IdHTTP1->ProxyParams->ProxyUsername = ProxyUser;
	  IdHTTP1->ProxyParams->ProxyPassword = ProxyPassword;
   }

   IdHTTP1->ConnectTimeout                = ConnectTimeout*1000;
   IdHTTP1->ReadTimeout                   = ConnectTimeout*1000;

   TMemIniFile* ini = new TMemIniFile( ".\\finam.dat");
   ini->ReadSections( ComboBox1->Items);

   ComboBox1->ItemIndex = 0;
   ComboBox1Change( NULL);

   delete ini;
}
//---------------------------------------------------------------------------
void __fastcall TFormTikers::FormKeyPress(TObject *Sender, wchar_t &Key)
{
   if( Key == VK_ESCAPE )	Close();
}
//---------------------------------------------------------------------------
void __fastcall TFormTikers::ComboBox1Change(TObject *Sender)
{
  TMemIniFile* ini = new TMemIniFile( ".\\finam.dat");
  TStringList*  s1 = new TStringList;


	ValueListEditor1->Strings->Clear();
	ini->ReadSectionValues( ComboBox1->Text, s1);
	s1->Sort();

	ValueListEditor1->Strings = s1;

  delete s1;
  delete ini;
}
//---------------------------------------------------------------------------
void __fastcall TFormTikers::Button1Click(TObject *Sender)
{
   down_tikers_finam();

   TMemIniFile* ini = new TMemIniFile( ".\\finam.dat");
   ini->ReadSections( ComboBox1->Items);

   ComboBox1->ItemIndex = 0;
   ComboBox1Change( NULL);

   delete ini;
}
//---------------------------------------------------------------------------
void TFormTikers::down_tikers_finam()
{
  TFileStream*  strm = new TFileStream( "$temp$.tmp", fmCreate);
  TStringList*  id   = new TStringList;
  TStringList*  name = new TStringList;
  TStringList*  tikr = new TStringList;
  TStringList*  sect = new TStringList;
  AnsiString    s_sec;
  int           i_sec;
  char          *str,*mstr,*p1,*p2;
  FILE*         ff, *out;
  char          s_out[300];


	Panel1->Caption = "Down tikers. Please wait...";
	Panel1->Visible = true;
	Panel1->Update();
	try { IdHTTP1->Get( "http://www.finam.ru/scripts/export.js", strm); }
	catch( Exception &e )
	{
	   Panel1->Visible = false;
	   MessageBox( Handle, "Ошибка при загрузке файла: http://www.finam.ru/scripts/export.js\nПовторите попытку ещё раз...", "FINAM.RU", MB_OK|MB_ICONERROR);
	   delete strm;
       remove( "$temp$.tmp");
	   return;
	}
	delete strm;

	Panel1->Caption = "Parsing file...";
	Panel1->Update();

	try{

	if( (ff = fopen( "$temp$.tmp", "rt")) != NULL )
	{
	   str = (char*)malloc( sizeof(char)*500000);
	   out = fopen( ".\\finam.tmp", "wt");

	   if( fgets( str, 500000, ff) != NULL )
	   {
		  mstr = strchr( str, '(')+1;
		  p1 = strstr( str, ");");
		  *p1 = '\0';
		  id->Delimiter = ',';
		  id->DelimitedText = mstr;
	   }

	   if( fgets( str, 500000, ff) != NULL )
	   {
		  mstr = strchr( str, '(')+1;
		  p1 = strstr( str, ");");
		  *p1 = '\0';
		  p1 = strchr( mstr, '\'');
		  p2 = strchr( p1+1, '\'');
		  do{
			  *p2 = '\0';
			  name->Add( p1+1);

			  p1 = strchr( p2+1, '\'');
			  if(p1) p2 = strchr( p1+1, '\'');
			} while( p1 );
	   }

	   if( fgets( str, 500000, ff) != NULL )
	   {
		  mstr = strchr( str, '(')+1;
		  p1 = strstr( str, ");");
		  *p1 = '\0';
		  p1 = strchr( mstr, '\'');
		  p2 = strchr( p1+1, '\'');
		  do{
			  *p2 = '\0';
			  tikr->Add( p1+1);

			  p1 = strchr( p2+1, '\'');
			  if(p1) p2 = strchr( p1+1, '\'');
			} while( p1 );
	   }

	   if( fgets( str, 500000, ff) != NULL )
	   {
		  mstr = strchr( str, '(')+1;
		  p1 = strstr( str, ");");
		  *p1 = '\0';
		  sect->Delimiter = ',';
	      sect->DelimitedText = mstr;
	   }

	   fclose( ff);
	   free( str);
	   remove( "$temp$.tmp");

	   if( id->Count != 0 || name->Count != 0 || tikr->Count != 0 || sect->Count != 0 )
	   {
		  for( int i=0; i < 24; i++)
		  {
			switch( i )
			{
			  case 0 : s_sec = "[ММВБ Акции]\n";                  i_sec = 1;  break;
			  case 1 : s_sec = "[ММВБ ПИФы]\n";                   i_sec = 29; break;
			  case 2 : s_sec = "[ММВБ облигации]\n";              i_sec = 2;  break;
			  case 3 : s_sec = "[ММВБ Внесписочные облигации]\n"; i_sec = 12; break;
			  case 4 : s_sec = "[РТС]\n";                         i_sec = 3;  break;
			  case 5 : s_sec = "[РТС-GAZ]\n";                     i_sec = 10; break;
			  case 6 : s_sec = "[РТС-GTS]\n";                     i_sec = 11; break;
			  case 7 : s_sec = "[RTS Board]\n";                   i_sec = 20; break;
			  case 8 : s_sec = "[RTS Standard]\n";                i_sec = 38; break;
			  case 9 : s_sec = "[Фьючерсы ФОРТС]\n";              i_sec = 14; break;
			  case 10: s_sec = "[Валюты]\n";                      i_sec = 5;  break;
			  case 11: s_sec = "[Индексы]\n";                     i_sec = 6;  break;
			  case 12: s_sec = "[Фьючерсы]\n";                    i_sec = 7;  break;
			  case 13: s_sec = "[АДР]\n";                         i_sec = 8;  break;
			  case 14: s_sec = "[Сырье]\n";                       i_sec = 24; break;
			  case 15: s_sec = "[СПФБ]\n";                        i_sec = 9;  break;
			  case 16: s_sec = "[ФОРТС Архив]\n";                 i_sec = 17; break;
			  case 17: s_sec = "[ММВБ Архив]\n";                  i_sec = 16; break;
			  case 18: s_sec = "[РТС Архив]\n";                   i_sec = 18; break;
			  case 19: s_sec = "[Акции США]\n";                   i_sec = 25; break;
			  case 20: s_sec = "[US Bonds/Notes]\n";              i_sec = 26; break;
			  case 21: s_sec = "[Отрасли экономики США]\n";       i_sec = 27; break;
			  case 22: s_sec = "[ETF]\n";                         i_sec = 28; break;
			  case 23: s_sec = "[Индексы мировой экономики]\n";   i_sec = 30; break;
			}

			fputs( s_sec.c_str(), out);

			for( int j=0; j < id->Count; j++)
			{
			  if( i_sec == sect->Strings[j].ToInt() )
			  {
				sprintf( s_out, "%s=%s,%s\n", tikr->Strings[j].c_str(),id->Strings[j].c_str(),name->Strings[j].c_str());
				fputs( s_out, out);
			  }
			}
		  }

		  ComboBox1->ItemIndex = 0;
		  ComboBox1Change( NULL);
		  Panel1->Visible = false;

		  fclose( out);

		  remove( ".\\finam.dat");
		  rename( ".\\finam.tmp", ".\\finam.dat");
		  delete id;
		  delete name;
		  delete tikr;
		  delete sect;
		  return;
	   }
	}
	else
	{
	  Panel1->Visible = false;
	  delete id;
	  delete name;
	  delete tikr;
	  delete sect;
	  return;
	}

	}
	catch(...)
	{
	   MessageBox( Handle, "Ошибка конвертации файла export.js", "FINAM.RU", MB_OK|MB_ICONERROR);

	   Panel1->Visible = false;
	   remove( "$temp$.tmp");
	   remove( ".\\finam.tmp");
	   delete id;
	   delete name;
	   delete tikr;
	   delete sect;
	   return;
	}
}
//---------------------------------------------------------------------------


