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

#include <vcl.h>
#pragma hdrstop

#include "UWatchMain.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TMainForm *MainForm;
TThreadCk ThreadCk[MAX_MACHINE]  ;
AnsiString dertime1;
TDataSet *DataSet;
TQuery *Query1;


byte baBill[320];// = new char[320];
byte btyZipcode[6];// = new char[6];
byte btyrespMsg[80];// = new char[80];
byte btyTelnum[20];// = new char[20];
byte btyXpos[10];// = new char[10];
byte btyYpos[10];// = new char[10];
byte btyAddr[80];// = new char[80] ;
byte btyPoiinfo[80];// = new char[80];
byte btyFiller[30];// = new char[30];

//---------------------------------------------------------------------------
__fastcall TMainForm::TMainForm(TComponent* Owner)
        : TForm(Owner)
{

    try{
        Database1->AliasName = "abc";
        Database1->DatabaseName = "abc";
        Database1->LoginPrompt = false;
        Database1->Params->Add("DATABASE NAME=");
        Database1->Params->Add("USER NAME=sa");
        Database1->Params->Add("ODBC DSN=MASTERCAR");
        Database1->Params->Add("OPEN MODE=READ/WRITE");
        Database1->Params->Add("BATCH COUNT=200");
        Database1->Params->Add("LANGDRIVER=");
        Database1->Params->Add("MAX ROWS=-1");
        Database1->Params->Add("SCHEMA CACHE DIR=");
        Database1->Params->Add("SCHEMA CACHE SIZE=8");
        Database1->Params->Add("SCHEMA CACHE TIME=-1");
        Database1->Params->Add("SQLPASSTHRU MODE=SHARED AUTOCOMMIT");
        Database1->Params->Add("SQLQRYMODE=");
        Database1->Params->Add("ENABLE SCHEMA CACHE=FALSE");
        Database1->Params->Add("ENABLE BCD=FALSE");
        Database1->Params->Add("ROWSET SIZE=20");
        Database1->Params->Add("BLOBS TO CACHE=64");
        Database1->Params->Add("BLOB SIZE=32");
        Database1->Params->Add("PASSWORD=");

        Database1->Connected = true;
        ListBox1->Items->Add("DB 연결 성공");
   }catch(Exception &e){

   }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::IdTCPServer1Execute(TIdPeerThread *AThread)
{
    AnsiString strReadpacket="", DateF ;
    int Icount, MsgLength ;
    //byte *GetMsg = new char[320];
    //byte *SendMsg = new char[320];
    byte GetMsg[320];
    byte SendMsg[320];

    AnsiString strGetTel="";
    Query1 = new TQuery(Application);

    int j = 1;
    try{
        while (AThread->Connection->Connected() ) {
            //ListBox1->Items->Add("[" + DateF + "]:  클라이언트가 접속하였습니다");
            DateF = TDateTime().CurrentDateTime();
            LogWrite("[" + DateF + "]: 클라이언트가 접속하였습니다");

            AThread->Connection->ReadBuffer(GetMsg,320);
            strReadpacket = (char*)GetMsg;

            for(int i = 84; i < 104; i++){
    		    if(strReadpacket.SubString(i, i+1) != " "){
                    strGetTel = strReadpacket.SubString(84,j).Trim();
                    j++;
                }
            }
            j = 0;
            strcpy(SendMsg,analPacket(strGetTel));
            AThread->Connection->WriteBuffer(SendMsg ,320);

         }
    }catch(...){

        delete[] btyZipcode;
        delete[] btyrespMsg;
        delete[] btyTelnum;
        delete[] btyXpos;
        delete[] btyYpos;
        delete[] btyAddr;
        delete[] btyPoiinfo;
        delete[] btyFiller;
        delete[] baBill;
        AThread->Connection->Disconnect();
        //ListBox1->Items->Add("[" + DateF + "]:  클라이언트가 종료하였습니다");
        LogWrite("[" + DateF + "]:  클라이언트가 종료하였습니다");
        AThread->Data = NULL;

    }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::FormCreate(TObject *Sender)
{
    IdTCPServer1->Active = true ;
}
//---------------------------------------------------------------------------


void __fastcall TMainForm::LogWrite(AnsiString Check)
{
    TFileStream *Stream ;
    AnsiString  FileName ;
    AnsiString  DateF ;

    DateF = FormatDateTime("yyyymmdd hh-nn-ss",Now()) + " "+Check+"\r\n";
    FileName = ExtractFileDir(ParamStr(0)) + "\\LogS.txt" ;
    if (!FileExists(FileName))  Stream = new TFileStream(FileName,fmCreate) ;
    else Stream = new TFileStream(FileName,fmOpenReadWrite | fmShareDenyWrite) ;
    Stream->Seek(0,soFromEnd) ;
    Stream->Write(DateF.c_str(),DateF.Length()) ;
    Stream->Free() ;

}

char* __fastcall TMainForm::analPacket(AnsiString recvTelNum)
{
    //TODO: Add your source code here
    AnsiString zipcode = NULL;
    AnsiString getTime = NULL;
	AnsiString SComment = NULL;
    AnsiString xPosition = NULL;
    AnsiString yPosition = NULL;
    AnsiString getAddr = "";
    AnsiString zipcode1 = NULL;
    AnsiString zipcode2 = NULL;
    AnsiString result = NULL;
    AnsiString responseMessage="";
    AnsiString poiinfo = " ";
    AnsiString dertime1 = NULL;
    AnsiString filler = " ";
    AnsiString failblk=" ";



	double dertime=0;
	double todayGetTime = 0;
    char *token;


	AnsiString sql;
    AnsiString today1, DateF;
    AnsiString dertime2;

    DateF = TDateTime().CurrentDateTime();
    today1 = FormatDateTime("yyyymmddhhnnss", TDateTime().CurrentDateTime());
    todayGetTime = today1.ToDouble();
    dertime = todayGetTime-500;


    Query1->DatabaseName = "abc";
    Query1->Close();
    Query1->SQL->Clear();

	sql = "Select * from ALbsLog where STelnum = '"+recvTelNum+"' and stelcom <> 'NO' and SGetTime >= '"+dertime +"' Order by SGetTime desc ";

    Query1->SQL->Add(sql);

    try{
        Query1->Open();
    }catch(Exception &e){
        Query1->Close();
    }

    if(Query1->Eof){


    }else{

        getTime = Query1->FieldByName("SGetTime")->AsString;
        SComment = Query1->FieldByName("SComment")->AsString;
    }
    //SComment에서 해당 값을 가져온다.
    //데이터베이스를 통해서 SComment 값은 대충 이렇습니다.
    //0111231111#ABC#37.529167#126.871944#20041123133102#123456#가나다라마 바사 아자차카타
    //여기까지는 잘 되므로 SComment값을 위의 값과 대입시켜도 무방합니다.
    
    char *Temp = new char[SComment.Length()];
//    strcpy(Temp, "");


    strcpy(Temp, SComment.c_str());

    strtok(Temp,"#");
    strtok(NULL,"#");
    xPosition = strtok(NULL,"#");
    yPosition = strtok(NULL,"#");
    strtok(NULL,"#");
    zipcode = strtok(NULL,"#");
    getAddr = strtok(NULL,"#");

    //delete[] Temp;



    if(getAddr != ""){

        responseMessage = "정상 조회 되었습니다.";

        //바이트 배열에 디비에서 뽑아온 정보를 넣고 나머지 바이트는 공백으로 채우는 부분


        strcpy(btyAddr, getAddr.c_str());
        strcpy(btyZipcode, zipcode.c_str());
        strcpy(btyrespMsg, responseMessage.c_str());
        strcpy(btyTelnum,  recvTelNum.c_str());
        strcpy(btyXpos, xPosition.c_str());
        strcpy(btyYpos, yPosition.c_str());
        strcpy(btyPoiinfo, "");
        strcpy(btyFiller, "");
       /* sprintf(btyZipcode, "%s", zipcode.c_str());
        sprintf(btyTelnum, "%s",recvTelNum.c_str());
        sprintf(btyrespMsg, "%s", responseMessage.c_str());
        sprintf(btyPoiinfo, "%s", "");
        sprintf(btyFiller,"%s", "");
         */
        for(int i = 0; i < 80 - getAddr.Length(); i++){

            strcat(btyAddr, " ");
        }
        for(int i = 0; i < 6 - zipcode.Length(); i++){
            strcat(btyZipcode, " ");
        }
        for(int i = 0; i < 80 - responseMessage.Length(); i++){
            strcat(btyrespMsg, " ");
        }
        for(int i = 0; i < 20 - recvTelNum.Length(); i++){
            strcat(btyTelnum, " ");
        }
        for(int i = 0; i < 10 - xPosition.Length(); i++){
            strcat(btyXpos, " ");
        }
        for(int i = 0; i < 10 - yPosition.Length(); i++){
            strcat(btyYpos, " ");
        }
        for(int i = 0; i < 80; i++){
            strcat(btyPoiinfo, " ");
        }
        for(int i = 0; i < 30; i++){
            strcat(btyFiller, " ");
        }

        strcpy(baBill, "96");
        strcat(baBill, "00");
        strcat(baBill, btyrespMsg);
        strcat(baBill, btyTelnum);
        strcat(baBill, btyXpos);
        strcat(baBill, btyYpos);
        strcat(baBill, btyZipcode);
        strcat(baBill, btyAddr);            //<=여기서 쓰레기값이 잘들어갑니다.
        strcat(baBill, btyPoiinfo);
        strcat(baBill, btyFiller);



    }else{  //해당 정보가 없으면

        responseMessage = "해당 정보가 없습니다";

        strcpy(btyAddr, getAddr.c_str());
        strcpy(btyZipcode, zipcode.c_str());
        strcpy(btyrespMsg, responseMessage.c_str());
        strcpy(btyTelnum,  recvTelNum.c_str());
        strcpy(btyXpos, xPosition.c_str());
        strcpy(btyYpos, yPosition.c_str());
        strcpy(btyPoiinfo, "");
        strcpy(btyFiller, "");

        for(int i = 0; i < 80 - getAddr.Length(); i++){

            strcat(btyAddr, " ");
        }
        for(int i = 0; i < 6 - zipcode.Length(); i++){
            strcat(btyZipcode, " ");
        }
        for(int i = 0; i < 80 - responseMessage.Length(); i++){
            strcat(btyrespMsg, " ");
        }
        for(int i = 0; i < 20 - recvTelNum.Length(); i++){
            strcat(btyTelnum, " ");
        }
        for(int i = 0; i < 10 - xPosition.Length(); i++){
            strcat(btyXpos, " ");
        }
        for(int i = 0; i < 10 - yPosition.Length(); i++){
            strcat(btyYpos, " ");
        }
        for(int i = 0; i < 80; i++){
            strcat(btyPoiinfo, " ");
        }
        for(int i = 0; i < 30; i++){
            strcat(btyFiller, " ");
        }

        strcpy(baBill, "96");
        strcat(baBill, "xx");
        strcat(baBill, btyrespMsg);
        strcat(baBill, btyTelnum);
        strcat(baBill, btyXpos);
        strcat(baBill, btyYpos);
        strcat(baBill, btyZipcode);
        strcat(baBill, btyAddr);
        strcat(baBill, btyPoiinfo);
        strcat(baBill, btyFiller);
    }
    //AnsiString a = baBill;
    //ListBox1->Items->Add("[" + DateF + "]:" + a);
    //배열을 320바이트로 정의해 놓았는데도 불구하고 320바이트가 초과해도 아무런 문제가
    //발생하지 않는 희안한일이...
    //프로그램을 종료하면 한꺼번에 에러가 뜨더군요.....ㅠ.ㅠ
    return baBill;
}
