<?php

define('COLOR_BLACK', 0x000000);
define('COLOR_RED', 0xff0000);
define('COLOR_GREEN', 0x00ff00);
define('COLOR_BLUE', 0x0000ff);
define('COLOR_WHITE', 0xffffff);

class Font
{
  public int $Size;
  public string $FileName;
  public int $Color;

  function __construct()
  {
    $this->Color = COLOR_BLACK;
    $this->FileName = '../../Common/Fonts/FreeSans.ttf';
    $this->Size = 10;
  }
}

class Pen
{
  public int $Color;
  public int $X;
  public int $Y;

  function __construct()
  {
    $this->Color = COLOR_BLACK;
    $this->X = 0;
    $this->Y = 0;
  }

}

class Brush
{
  public int $Color;

  function __construct()
  {
    $this->Color = COLOR_BLACK;
  }

}

class Image
{
  public $Image;
  public int $Type;
  public Font $Font;
  public Pen $Pen;
  public Brush $Brush;

  function __construct()
  {
    $this->Image = imagecreatetruecolor(1, 1);
    $this->Type = IMAGETYPE_PNG;
    $this->Pen = new Pen();
    $this->Font = new Font();
    $this->Brush = new Brush();
  }

  function SaveToFile(string $FileName): void
  {
    if ($this->Type == IMAGETYPE_JPEG)
    {
      imagejpeg($this->Image, $FileName);
    } else
    if ($this->Type == IMAGETYPE_GIF)
    {
      imagegif ($this->Image, $FileName);
    } else
    if ($this->Type == IMAGETYPE_PNG)
    {
      imagepng($this->Image, $FileName);
    }
  }

  function LoadFromFile(string $FileName): void
  {
    $ImageInfo = getimagesize($FileName);
    $this->Type = $ImageInfo[2];
    if ($this->Type == IMAGETYPE_JPEG)
    {
      $this->Image = imagecreatefromjpeg($FileName);
    } else
    if ($this->Type == IMAGETYPE_GIF)
    {
      $this->Image = imagecreatefromgif ($FileName);
    } else
    if ( $this->Type == IMAGETYPE_PNG)
    {
      $this->Image = imagecreatefrompng($FileName);
    }
  }

  function Output(): void
  {
    $this->SaveToFile(NULL);
  }

  function SetSize(int $Width, int $Height): void
  {
    $NewImage = imagecreatetruecolor($Width, $Height);
    imagecopy($NewImage, $this->Image, 0, 0, 0, 0, $this->GetWidth(), $this->GetHeight());
    imagedestroy($this->Image);
    $this->Image = $NewImage;
  }

  function GetWidth(): int
  {
    return imagesx($this->Image);
  }

  function GetHeight(): int
  {
    return imagesy($this->Image);
  }

  function TextOut(int $X, int $Y, string $Text): void
  {
    imagettftext($this->Image, $this->Font->Size, 0, $X, $Y, $this->ConvertColor($this->Font->Color), $this->Font->FileName, $Text);
  }

  function ConvertColor(int $Color): int
  {
    return imagecolorallocate($this->Image, ($Color >> 16) & 0xff, ($Color >> 8) & 0xff, $Color & 0xff);
  }

  function FillRect(int $X1, int $Y1, int $X2, int $Y2): void
  {
    imagefilledrectangle($this->Image, $X1, $Y1, $X2, $Y2, $this->ConvertColor($this->Brush->Color));
  }

  function Line(int $X1, int $Y1, int $X2, int $Y2): void
  {
    imageline($this->Image, $X1, $Y1, $X2, $Y2, $this->ConvertColor($this->Pen->Color));
  }
}
