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


#pragma hdrstop

#include "ContentProviderThread.h"
#include "MainUnit.h"

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

#pragma package(smart_init)

TContentProviderThread::TContentProviderThread(TStream *SourceStream, TStream *DestStream, unsigned int Speed) :
   TThread(false)
{
   FSourceStream = SourceStream;
   FDestStream = DestStream;

   FSpeed = Speed;
   FDelay = 100;

   FBufferSize = FSpeed * FDelay;
   FBufferSize = FBufferSize / 1000;

   FBuffer = new TMemoryStream;
}

void __fastcall TContentProviderThread::Execute()
{
   FLoadedBytes = 0;

   while (!FStop)
   {
      PrepareBuffer();

      if (FBuffer->Size > 0)
      {
         DoWrite();
         Sleep(FDelay);
      }

      Synchronize(UpdateGUI);
   }

   FSourceStream->Free();
   FDestStream->Free();

   FBuffer->Free();

   FreeOnTerminate = true;
}

void __fastcall TContentProviderThread::PrepareBuffer()
{
   unsigned char* pBuffer = new unsigned char[FBufferSize];

   int nReadBytes = FSourceStream->Read(pBuffer, FBufferSize);

   if (0 == nReadBytes)
      FStop = true;
   else
   {
     for (int i = 0; i < nReadBytes; i++)
        pBuffer[i] ^= Mask;

     FBuffer->Write(pBuffer, nReadBytes);
     FBuffer->Position = 0;
   }

   delete[] pBuffer;
}

void __fastcall TContentProviderThread::DoWrite()
{
   int nWrittenBytes = FDestStream->Write(FBuffer->Memory, FBuffer->Size);

   if (0 == nWrittenBytes)
      FStop = true;
   else
      FLoadedBytes += nWrittenBytes;
}

void __fastcall TContentProviderThread::UpdateGUI()
{
   // Update GUI
   MainForm->LabelStatus->Caption = "Status: " + IntToStr(FLoadedBytes) + " bytes loaded...";

   if (FStop)
      MainForm->LabelStatus->Caption += " (finished)";
}

