<?php
/**
 * @copyright (c) Kufer Software GmbH, Loisachstrasse 4, D-84453 Mühldorf
 */

use Kufer\Web\Classes\Api\ImageApi;

class ImageApiTest extends \PHPUnit\Framework\TestCase
{
  /**
   * Sets up the fixture, for example, opens a network connection.
   * This method is called before a test is executed.
   */
  protected function setUp(): void
  {
    \DBWorkBASysSettings::$TestEnforceVsb = false;
  }

  /**
   * Tears down the fixture, for example, closes a network connection.
   * This method is called after a test is executed.
   */
  protected function tearDown(): void
  {
  }

  private function createWhiteImage()
  {
    $whiteImg = imagecreate(50, 50);
    $white = imagecolorallocate($whiteImg, 0xFF, 0xFF, 0xFF);
    imagefilledrectangle($whiteImg, 0, 0, 50, 50, $white);

    return $whiteImg;
  }

  private function createBlackImage()
  {
    $img = imagecreate(50, 50);
    $color = imagecolorallocate($img, 0, 0, 0);
    imagefilledrectangle($img, 0, 0, 50, 50, $color);

    return $img;
  }

  private function createHalfBlackImage()
  {
    $whiteImg = $this->createBlackImage();
    $white = imagecolorallocate($whiteImg, 0xFF, 0xFF, 0xFF);
    imagefilledrectangle($whiteImg, 0, 0, 50, 25, $white);

    return $whiteImg;
  }

  /**
   * @test
   * @return void
   */
  public function diffWhiteImages()
  {
    $this->assertTrue(extension_loaded('gd'));

    $whiteImg = $this->createWhiteImage();

    $this->assertEquals(0.0, ImageApi::diff($whiteImg, $whiteImg, 50, 50));
    $this->assertEquals(0.0, ImageApi::diffToWhite($whiteImg, 50, 50));
  }

  /**
   * @test
   * @return void
   */
  public function diffBlackAndWhite()
  {
    $this->assertTrue(extension_loaded('gd'));

    $whiteImg = $this->createWhiteImage();
    $blackImg = $this->createBlackImage();

    $diff0 = ImageApi::diff($whiteImg, $blackImg, 50, 50);
    $diff1 = ImageApi::diff($whiteImg, $blackImg, 50, 50);
    $this->assertEquals($diff0, $diff1);

    $this->assertEquals(0.5, $diff0);
  }

  /**
   * @test
   * @return void
   */
  public function diffHalfBlackAndWhiteImage()
  {
    $white = $this->createWhiteImage();
    $halfWhite = $this->createHalfBlackImage();

    $diff = ImageApi::diff($white, $halfWhite, 50, 50);
    $this->assertGreaterThanOrEqual(0.24, $diff);
    $this->assertLessThanOrEqual(0.26, $diff);
  }
}
