//---------------------------------------------------------------------------

#include <vcl.h>
#include <mshtml.h>
#include <vector>
#include <dir.h>
using namespace std;
#pragma hdrstop

#include "Unit1.h"
#include "Unit2.h"

#include "Unit4.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "SHDocVw_OCX"
#pragma resource "*.dfm"
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
  db_Process = false;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormCreate(TObject *Sender)
{
  TTable *table = new TTable(Form1);
  table->DatabaseName = "Hotels_Db";
  table->TableName = "Going";
  try
    {
      table->Open();
    }
  catch(...)
    {
      ShowMessage("Table Open Exception");
    }
  if ( table->RecordCount != 0 )
    db_Process = true;
  else
    db_Process = false;
  table->Close();
  delete table;
  if(FAILED(::CoInitialize(NULL)))
    ShowMessage("COM Init ¿¡·¯");
  UrlList = new TStringList();
  mode = 0;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::Button2Click(TObject *Sender)
{
  if ( db_Process == false )
  {
    LineCount = 0;
    if ( Memo2->Lines->Count > 1 )
      GetHotelList(0);
  }
  else
    DbProcess();

}
//---------------------------------------------------------------------------
void __fastcall TForm1::GetHotelList(int idx )
{
  mode = 1;
  Current_AirPort = Memo2->Lines->Strings[idx];
  SeedUrl = "http://dps1.travelocity.com/cannonball.ctl?Service=TRAVELOCITY";
  SeedUrl += "&SearchPath=hots&old_cb=N&SEQ=1754116789106066110719&mode=1";
  SeedUrl += "&airport=" + Current_AirPort + "&state=";
  SeedUrl += "&ckin_dt_mon=Sep&ckin_dt_dy=1";
  SeedUrl += "&ckout_dt_mon=Sep&ckout_dt_dy=3";
  SeedUrl += "&pax_cnt=1&mode=2";
  WideString w_url = SeedUrl;

  CppWebBrowser1->Navigate(w_url);

//  HotelListParaser(SeedUrl);

}
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
  static int i = 0;

  if ( i == 60 )
    {
      i = 0;
      GetHotelList(++LineCount);
    }
  else
    i ++;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::DbProcess(void)
{
  if ( Table1->Active )
    Table1->Close();

  Table1->DatabaseName = "Hotels_Db";
  Table1->TableName = "Going";
  try
    {
      Table1->Open();
    }
  catch(...)
    {
      ShowMessage("Table Open Exception");
    }
  if ( Table1->RecordCount != 0 )
    for ( int i = 0 ; i < Table1->RecordCount ; i++ )
      {
        Hotel_Url temp;
        temp.Url = Table1->FieldByName("Url")->AsString;
        temp.Airport = Table1->FieldByName("AirPort")->AsString;
        Hotel_Que.push_back(temp);
        Table1->Next();
      }
  Table1->Close();
  GetHotelDesc();
}
//---------------------------------------------------------------------------
void __fastcall TForm1::GetHotelDesc(void)
{
  if ( !Hotel_Que.empty() )
    {
      Hotel_Url temp = Hotel_Que[Hotel_Que.size()-1];
      Hotel_Que.pop_back();
      THotelDescParser *HotelDescParser = new THotelDescParser();
      HotelDescParser->PutUrl(temp.Url);
      HotelDescParser->HotelDescParser();

/*      if ( !Table2->Active )
        Table2->Open();
      Table2->Insert();
      Table2->FieldByName("Airport")->AsString        = temp.Airport;
      Table2->FieldByName("Url")->AsString            = temp.Url;
      Table2->FieldByName("HotelName")->AsString      = HotelDescParser->Get_HotelName();
      Table2->FieldByName("HotelInfo")->AsString     = HotelDescParser->Get_Hotel_Info();
      Table2->FieldByName("Transportation")->AsString = HotelDescParser->Get_Transportation();
      Table2->FieldByName("Directions")->AsString     = HotelDescParser->Get_Directions();
      Table2->FieldByName("Property_Information")->AsString = HotelDescParser->Get_Property_Information();
      Table2->FieldByName("Services")->AsString       = HotelDescParser->Get_Services();
      Table2->FieldByName("Dininng")->AsString         = HotelDescParser->Get_Dining();
      Table2->FieldByName("Ratings_Awards")->AsString = HotelDescParser->Get_Ratings_Awards();
      Table2->FieldByName("Attractions")->AsString    = HotelDescParser->Get_Attractions();
      Table2->Post();*/
/*      TLogFile* HotelInfo = new TLogFile("Hotels.txt");
      HotelInfo->WriteNavigation("QQQ");
      HotelInfo->WriteNavigation(HotelDescParser->Get_HotelName());
      HotelInfo->WriteNavigation(temp.Airport);
      HotelInfo->WriteNavigation(temp.Url);
      HotelInfo->WriteNavigation(HotelDescParser->Get_Hotel_Info());
      HotelInfo->WriteNavigation(HotelDescParser->Get_Transportation());
      HotelInfo->WriteNavigation(HotelDescParser->Get_Directions());
      HotelInfo->WriteNavigation(HotelDescParser->Get_Property_Information());
      HotelInfo->WriteNavigation(HotelDescParser->Get_Services());
      HotelInfo->WriteNavigation(HotelDescParser->Get_Dining());
      HotelInfo->WriteNavigation(HotelDescParser->Get_Ratings_Awards());
      HotelInfo->WriteNavigation(HotelDescParser->Get_Attractions());
      delete HotelInfo;*/

      delete HotelDescParser;
    }
  else
    Timer1->Enabled = true;
  Timer2->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer2Timer(TObject *Sender)
{
  static int i = 0;

  if ( i == 60 )
    {
      i = 0;
      GetHotelDesc();
    }
  else
    i ++;
}
//---------------------------------------------------------------------------

void __fastcall TForm1::FormClose(TObject *Sender, TCloseAction &Action)
{
  Table1->DatabaseName = "Hotels_Db";
  Table1->TableName = "Going";
  try
    {
      Table1->Open();
    }
  catch(...)
    {
      ShowMessage("Table Open Exception");
    }
  if ( Table1->RecordCount != 0 )
    for ( int i = 0 ; i < Table1->RecordCount ; i++ )
      {
        Table1->Delete();
        Table1->Post();
      }
   Table1->Insert();
   for ( size_t i = 0 ; i < Hotel_Que.size() ; i ++ )
    {
      Hotel_Url temp = Hotel_Que[i];
      Table1->FieldByName("Url")->AsString = temp.Url;
      Table1->FieldByName("AirPort")->AsString = temp.Airport;
      Table1->Post();
    }
  Table1->Close();
  GetHotelDesc();
  if ( UrlList != NULL )
          delete UrlList;
  urlMap.clear();
  nextUrlMap.clear();
  GoneQue.clear();
  ::CoUninitialize();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::HotelListParaser (LPDISPATCH pDoc)
{
  HRESULT hr=S_OK;
  LPDISPATCH Document = pDoc;
  IHTMLDocument2* Document2;
  IHTMLElementCollection* pCollection;

  hr = Document->QueryInterface(IID_IHTMLDocument2,(**void)&Document2);
  if ( hr == S_OK )
    {
      Document2->get_anchors(&pCollection);
      Document2->Release();
    }

  WideString w_url;
  AnsiString url;
  WideString w_Key;
  AnsiString Key;

  long Anchor_Cnt;
  pCollection->get_length(&Anchor_Cnt);
  for (int nIndex = 0; nIndex < Anchor_Cnt; nIndex++ )
    {
      Variant vIndex((long)nIndex);
      Variant vNull;
      hr = pCollection->item(vIndex, vNull, &Document);
      if  ( hr  == S_OK )
        {
          if (Document != NULL)
            {
              IHTMLAnchorElement *pAnchor;
              IHTMLElement *pElement;
              hr = Document->QueryInterface(IID_IHTMLAnchorElement,(void**)&pAnchor);
              if ( hr == S_OK )
                {
                  pAnchor->get_href(&w_url);

                  url = w_url.c_bstr();
                  if ( url != "" )
                    {
                      urlMap[url]++;
                      if ( url.Pos("hotsavail.ctl?") != 0  )
                        {
                          hr = pAnchor->QueryInterface(IID_IHTMLElement,(void**)&pElement);
                          if ( hr == S_OK )
                            {
                              pElement->get_innerText(&w_Key);
                              Key = w_Key.c_bstr();

                              if ( Key == "Next" )
                                nextUrlMap[url]++;
                              pElement->Release();

                            }
                        }
                    }
                  pAnchor->Release();
                }
              Document->Release();
            }
        }
      pCollection->Release();
    }

  pCollection->Release();
  pDoc->Release();

  map<AnsiString , int > :: iterator itr;
  AnsiString temp;
  for ( itr = urlMap.begin() ; itr != urlMap.end() ; itr ++ )
    {
      temp = itr->first;
      if ( temp.Pos("hotsdetail.ctl?") != 0 )
        UrlList->Add(temp);
    }

  for ( itr = nextUrlMap.begin() ; itr != nextUrlMap.end() ; itr++ )
    {
      temp = itr->first;
      if ( itr->second <= 2)
        {
          GoneQue.push_back(temp);
          itr->second++;
        }
    }
  ::CoUninitialize();

  int UrlCount;
  UrlCount = UrlList->Count;

  Memo1->Lines->Add("First Page");
  int cnt=2;

  while ( IsNextPage() )
    {
      GetNextPage();
      Memo1->Lines->Add(IntToStr(cnt) + "th Page");
      cnt++;
    }

  for ( int i = 0 ; i < UrlCount ; i++ )
    {
      Hotel_Url temp;
      temp.Url = UrlList->Strings[i];
      temp.Airport = Current_AirPort;
      Hotel_Que.push_back(temp);
    }
  GetHotelDesc();
  Timer1->Enabled = true;
}
//---------------------------------------------------------------------------
void __fastcall TForm1::GetNextPage ( void )
{
  AnsiString url;
  if ( !GoneQue.empty() )
    {
      url = GoneQue[GoneQue.size()-1];
      GoneQue.pop_back();
      UrlList->Clear();
      WideString wurl = url;
      CppWebBrowser1->Navigate(wurl);
    }
}
//---------------------------------------------------------------------------

void __fastcall TForm1::CppWebBrowser1NewWindow2(TObject *Sender,
      LPDISPATCH *ppDisp, VARIANT_BOOL *Cancel)
{
  *Cancel = vaFalse;
}
//---------------------------------------------------------------------------


void __fastcall TForm1::CppWebBrowser1DocumentComplete(TObject *Sender,
      LPDISPATCH pDisp, Variant *URL)
{
  if ( mode = 1)
    HotelListParaser(pDisp);
}
//---------------------------------------------------------------------------

