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

#include <vcl.h>
#pragma hdrstop

#include "MainUnit.h"

#include <msxmldom.hpp>
#include <XMLDoc.hpp>
#include <xmldom.hpp>
#include <XMLIntf.hpp>

#include "ContentProviderThread.h"
#include "URLFormUnit.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "FlashPlayerControl"
#pragma resource "*.dfm"
#pragma resource "res\\movie.res"
TMainForm *MainForm;

class TMessageTimer : public TTimer
{
private:
   WideString m_Msg;

private:
   void __fastcall TimerHandler(TObject* Sender)
   {
      Enabled = false;

      ShowMessage(m_Msg);

      Free();
   }

public:
   TMessageTimer(Classes::TComponent* AOwner, WideString msg) :
      TTimer(AOwner),
      m_Msg(msg)
   {
      OnTimer = TimerHandler;

      Interval = 1;
      Enabled = true;
   }
};

//---------------------------------------------------------------------------
__fastcall TMainForm::TMainForm(TComponent* Owner)
        : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::ButtonLoadClick(TObject *Sender)
{
   TButton& button = *(TButton*)Sender;
   TPoint pt;
   pt.x = button.Left;
   pt.y = button.Top + button.Height;
   pt = ClientToScreen(pt);

   PopupMenuPlay->Popup(pt.x, pt.y);
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::FlashPlayerControl1FlashCall(TObject *ASender,
      const WideString request)
{
   // BTW: don't call ShowMessage in handlers of flash events, like fscommand, flashcall
   // you can use TMessageTimer to show alerts, see TMessageTimer at the top of this file

   TXMLDocument* doc = new TXMLDocument("");

   _di_IXMLDocument d;
   doc->GetInterface(d);

   d->LoadFromXML(request);

   WideString RequestName = doc->DocumentElement->Attributes["name"];

   if (RequestName == WideString("onMetaData"))
      // Metadata (i.e. information about video) available
   {
        WideString XMLDuration = FlashPlayerControl1->CallFunction("<invoke name=\"getDuration\" returntype=\"xml\"><arguments></arguments></invoke>");
        d->LoadFromXML(XMLDuration);
        WideString strDuration = doc->DocumentElement->Text;
        float Duration = -1;
        char OldDecimalSeparator = DecimalSeparator;
        __try
        {
           DecimalSeparator = '.';

           Duration = StrToFloat(strDuration);

           TrackBarVideoPos->Max = (int)Duration;
           TimerUpdateProgress->Enabled = true;
        }
        __finally
        {
           DecimalSeparator = OldDecimalSeparator;
        }
   }
   else if (RequestName == WideString("onVideoStatus"))
      // Video status
   {
        WideString Status = doc->DocumentElement->ChildNodes->Nodes[0]->ChildNodes->Nodes[0]->Text;

        // Possible values:
        /*
                NetConnection.Connect.Success - connected to video source successfully
                NetStream.Play.Start - ready to play
                NetStream.Play.StreamNotFound - video source not found
                NetStream.Play.Stop - playing stopped
                NetStream.Buffer.Empty - video buffer empty
                NetStream.Buffer.Full - video buffer full
        */
        if (Status == WideString("NetConnection.Connect.Success"))
        {
           LabelVideoStatus->Caption = "Connected";
        }
        else if (Status == WideString("NetStream.Play.Start"))
        {
           LabelVideoStatus->Caption = "Ready to play";
        }
        else if (Status == WideString("NetStream.Play.StreamNotFound"))
        {
           LabelVideoStatus->Caption = "Video source not found";
        }
        else if (Status == WideString("NetStream.Play.Stop"))
        {
           LabelVideoStatus->Caption = "Stopped";

           TimerUpdateProgress->Enabled = false;
        }
   }
}
//---------------------------------------------------------------------------
void __fastcall TMainForm::TimerUpdateProgressTimer(TObject *Sender)
{
   TXMLDocument* doc = new TXMLDocument("");

   _di_IXMLDocument d;
   doc->GetInterface(d);

        WideString XMLCurPos = FlashPlayerControl1->CallFunction("<invoke name=\"getCurrPosition\" returntype=\"xml\"><arguments></arguments></invoke>");
        d->LoadFromXML(XMLCurPos);
        WideString strCurPos = doc->DocumentElement->Text;
        float CurPos = -1;
        if (!TryStrToFloat(strCurPos, CurPos))
        {
           int n = strCurPos.Pos(".");
           if (-1 != n)
              strCurPos[n] = ',';

           if (TryStrToFloat(strCurPos, CurPos))
           {
              TrackBarVideoPos->Position = (int)CurPos;

              CHAR buf[1024];
              wsprintfA(buf, "%.2d:%.2d", (int)CurPos, (int)((CurPos - (int)CurPos) * 100) );
              LabelCurrentPosition->Caption = buf;
           }
        }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::LoadFLVfromafile1Click(TObject *Sender)
{
   if (OpenDialogFLV->Execute())
   {
        TResourceStream* rs = new TResourceStream(0, "VideoPlayer", "FLASH");
        FlashPlayerControl1->FlashVars = "type_video=flv&url=" + OpenDialogFLV->FileName + "&auto_play=" + ( CheckBoxAutoPlay->Checked ? "true" : "false" );
        FlashPlayerControl1->PutMovieFromStream(rs);
        delete rs;
   }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::LoadFLVembeddedintheprogram1Click(
      TObject *Sender)
{
   TResourceStream* rs = new TResourceStream(0, "VideoPlayer", "FLASH");
   FlashPlayerControl1->FlashVars = WideString("type_video=flv&url=http://FLV/FlashVideo.flv&auto_play=") + ( CheckBoxAutoPlay->Checked ? "true" : "false" );
   FlashPlayerControl1->PutMovieFromStream(rs);
   delete rs;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::FormCreate(TObject *Sender)
{
   Flashplayercontrol::SetGlobalOnLoadExternalResourceHandlerEx(ContentProvider);

   FlashPlayerControl1->AllowFullscreen = true;
   FlashPlayerControl1->BGColor = "#000000";

   TResourceStream* rs = new TResourceStream(0, "VideoPlayer", "FLASH");
   FlashPlayerControl1->PutMovieFromStream(rs);
   delete rs;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::ContentProvider(const WideString URL, TStream* Stream, bool& bHandled)
{
  if (URL == WideString("http://FLV/FlashVideo.flv"))
  {
    TContentProviderThread* ContentProviderThread =
        new TContentProviderThread(new TResourceStream(0, "FlashVideo","FLV"), Stream, 1024 * 1024);

    bHandled = true;
  }
}

void __fastcall TMainForm::ButtonPauseClick(TObject *Sender)
{
   FlashPlayerControl1->CallFunction("<invoke name=\"pauseVideo\" returntype=\"void\"><arguments></arguments></invoke>");
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::ButtonPlayClick(TObject *Sender)
{
   FlashPlayerControl1->CallFunction("<invoke name=\"resumeVideo\" returntype=\"void\"><arguments></arguments></invoke>");
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::ButtonBackClick(TObject *Sender)
{
   TXMLDocument* doc = new TXMLDocument("");

   _di_IXMLDocument d;
   doc->GetInterface(d);

   WideString XMLCurrentPosition = FlashPlayerControl1->CallFunction("<invoke name=\"getCurrPosition\" returntype=\"xml\"><arguments></arguments></invoke>");
   d->LoadFromXML(XMLCurrentPosition);
   WideString strCurrentPosition = doc->DocumentElement->Text;
   float CurrentPosition = -1;
   char OldDecimalSeparator = DecimalSeparator;
   __try
   {
      DecimalSeparator = '.';

      CurrentPosition = StrToFloat(strCurrentPosition);
   }
   __finally
   {
      DecimalSeparator = OldDecimalSeparator;
   }

   // Back, 5 seconds
   CurrentPosition -= 5;

   CHAR buf[1024];
   wsprintfA(buf, "<invoke name=\"seekVideo\" returntype=\"xml\"><arguments><number>%d</number></arguments></invoke>", (int)CurrentPosition);
   FlashPlayerControl1->CallFunction(buf);
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::ButtonForwardClick(TObject *Sender)
{
   TXMLDocument* doc = new TXMLDocument("");

   _di_IXMLDocument d;
   doc->GetInterface(d);

   WideString XMLCurrentPosition = FlashPlayerControl1->CallFunction("<invoke name=\"getCurrPosition\" returntype=\"xml\"><arguments></arguments></invoke>");
   d->LoadFromXML(XMLCurrentPosition);
   WideString strCurrentPosition = doc->DocumentElement->Text;
   float CurrentPosition = -1;
   char OldDecimalSeparator = DecimalSeparator;
   __try
   {
      DecimalSeparator = '.';

      CurrentPosition = StrToFloat(strCurrentPosition);
   }
   __finally
   {
      DecimalSeparator = OldDecimalSeparator;
   }

   // Forward, 5 seconds
   CurrentPosition += 5;

   CHAR buf[1024];
   wsprintfA(buf, "<invoke name=\"seekVideo\" returntype=\"xml\"><arguments><number>%d</number></arguments></invoke>", (int)CurrentPosition);
   FlashPlayerControl1->CallFunction(buf);
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::TrackBarVideoPosChange(TObject *Sender)
{
   if (::GetCapture() == TrackBarVideoPos->Handle)
   {
      CHAR buf[1024];
      wsprintfA(buf, "<invoke name=\"seekVideo\" returntype=\"xml\"><arguments><number>%d</number></arguments></invoke>", TrackBarVideoPos->Position);
      FlashPlayerControl1->CallFunction(buf);
   }
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::LoadFLVfromURL1Click(TObject *Sender)
{
   TURLForm* form = new TURLForm(this);

   form->Caption = "URL";

   form->Left = Left + Width / 2 - form->Width / 2;
   form->Top = Top + Height / 2 - form->Height / 2;

   if (form->ShowModal() == mrOk)
   {
      WideString FlashVars = "type_video=flv&url=" + form->URL + "&auto_play=";

      if (CheckBoxAutoPlay->Checked)
         FlashVars += "true";
      else
         FlashVars += "false";

      FlashPlayerControl1->FlashVars = FlashVars;

      TResourceStream* rs = new TResourceStream(0, "VideoPlayer", "FLASH");
      FlashPlayerControl1->PutMovieFromStream(rs);
      delete rs;
   }

   delete form;
}
//---------------------------------------------------------------------------

void __fastcall TMainForm::LoadFLVfromRTMPsource1Click(TObject *Sender)
{
   TURLForm* form = new TURLForm(this);

   form->Caption = "RTMP Source URL";

   form->Left = Left + Width / 2 - form->Width / 2;
   form->Top = Top + Height / 2 - form->Height / 2;

   if (form->ShowModal() == mrOk)
   {
      WideString FlashVars = "type_video=rtmp&url=" + form->URL + "&auto_play=";

      if (CheckBoxAutoPlay->Checked)
         FlashVars += "true";
      else
         FlashVars += "false";

      FlashPlayerControl1->FlashVars = FlashVars;

      TResourceStream* rs = new TResourceStream(0, "VideoPlayer", "FLASH");
      FlashPlayerControl1->PutMovieFromStream(rs);
      delete rs;
   }

   delete form;
}
//---------------------------------------------------------------------------

