//---------------------------------------------------------------------------
#include <fmx.h>
#pragma hdrstop

#include "Main.h"
#ifdef __ANDROID__
#include <Androidapi.Helpers.hpp>
#endif __ANDROID__
#include <System.Permissions.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.fmx"
TFormMain *FormMain;
//---------------------------------------------------------------------------
__fastcall TFormMain::TFormMain(TComponent* Owner)
  : TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::FormCreate(TObject *Sender)
{
  BarcodeDecoder = new TBarcodeDecoder();

#ifdef __ANDROID__
  DynamicArray<String> permissions;
  permissions.Length = 1;
  permissions[0] = JStringToString(TJManifest_permission::JavaClass->CAMERA);

  PermissionsService()->RequestPermissions(permissions,
    [this](const DynamicArray<String> APermissions, const DynamicArray<TPermissionStatus> AGrantResults)
    {
      ButtonStartStop->Enabled = ((AGrantResults.Length == 1) && (AGrantResults[0] == TPermissionStatus::Granted));
    });
#endif // __ANDROID__
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::FormDestroy(TObject *Sender)
{
  delete BarcodeDecoder;
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::Start()
{
  CameraComponent->Active = true;
  ButtonStartStop->Text = "Stop";
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::Stop()
{
  CameraComponent->Active = false;
  ButtonStartStop->Text = "Start";
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ButtonStartStopClick(TObject *Sender)
{
  try
  {
    if (!CameraComponent->Active)
      Start();
    else
      Stop();
  }
  catch (Exception &ex)
  {
    Stop();
    throw;
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::CameraComponentSampleBufferReady(TObject *Sender, const TMediaTime ATime)
{
  try
  {
    CameraComponent->SampleBufferToBitmap(ImageViewer->Bitmap, true);
    TDecodeResults Results = BarcodeDecoder->Decode(ImageViewer->Bitmap);

    if (Results.Length > 0)
      Memo->Lines->Clear();

    for (int I = 0; I < Results.Length; ++I)
    {
      Memo->Lines->Append(Results[I].FormatName + ": " + Results[I].Text);
      Memo->GoToTextEnd();
    }

    // TImageViewer workaround
    if (!WasRealignContent)
    {
      ImageViewer->RealignContent();
      WasRealignContent = true;
    }
  }
  catch (Exception &ex)
  {
    Memo->Lines->Clear();
    Memo->Lines->Append(ex.Message);
  }
}
//---------------------------------------------------------------------------
