//---------------------------------------------------------------------------
#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)
{
#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::Start()
{
  FObr->Active = true;
  CameraComponent->Active = true;
  ButtonStartStop->Text = "Stop";
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::Stop()
{
  CameraComponent->Active = false;
  FObr->Active = false;
  ButtonStartStop->Text = "Start";
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::CameraComponentSampleBufferReady(TObject *Sender, const TMediaTime ATime)
{
  CameraComponent->SampleBufferToBitmap(ImageViewer->Bitmap, true);
  CameraComponent->SampleBufferToBitmap(FObr->Picture, true);
  FObr->Scan();

  // TImageViewer workaround for Android and iOS
  if (!WasRealignContent)
  {
    ImageViewer->RealignContent();
    WasRealignContent = true;
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::FObrBarcodeDetected(TObject *Sender)
{
  Memo->Lines->Clear();
  for (int i = 0; i < FObr->BarcodeCount; ++i)
  {
    TObrSymbol *Barcode = FObr->Barcode[i];
    Memo->Lines->Append(Barcode->SymbologyName + Barcode->SymbologyAddonName + " " + Barcode->OrientationName + " " + Barcode->DataUtf8);
    Memo->GoToTextEnd();
  }
}
//---------------------------------------------------------------------------
void __fastcall TFormMain::ButtonStartStopClick(TObject *Sender)
{
  try
  {
    if (!FObr->Active)
      Start();
    else
      Stop();
  }
  catch(...)
  {
    Stop();
    throw;
  }
}
//---------------------------------------------------------------------------