<?php

declare(strict_types=1);
namespace Tests\git2;

use git2\git;
use git2\git_strarray;
use git2\Internal\Debug\Call;
use git2\Internal\FFI;

final class StrarrayTest extends GitTestCase
{

	public function testDefault(): void
	{
		$array = $this->createArray();
		$this->assertSame(3, $array->count);
		$this->assertSame(3, count($array));
		$this->assertSame('v1.0', $array[0]);
		$this->assertSame('v1.1.0', $array[1]);
		$this->assertSame('v1.1.1', $array[2]);
		$this->assertSame(['v1.0', 'v1.1.0', 'v1.1.1'], iterator_to_array($array));
	}

	public function testDispose(): void
	{
		$disposed = false;

		FFI::debug(function (Call $call) use(&$disposed): void {

			if ($call->function === 'git_strarray_dispose') {
				$disposed = true;
			}

		});

		$this->createArray();
		$this->assertTrue($disposed);
	}

	public function testCopy(): void
	{
		// Just to ensure that the original array has been free'd without side-effects.
		$copy = (function(): git_strarray {
			$array = $this->createArray();
			$this->assertOK(git::strarray_copy($copy, $array));
			$this->assertNotSame($copy, $array);
			return $copy;
		})();

		$this->assertSame(3, count($copy));
		$this->assertSame('v1.0', $copy[0]);
		$this->assertSame('v1.1.0', $copy[1]);
		$this->assertSame('v1.1.1', $copy[2]);
	}

	public function testOwned(): void
	{
		$strarray = git_strarray::from([
			'foo',
			'bar',
		]);

		$this->assertInstanceOf(git_strarray::class, $strarray);
		$this->assertSame(2, count($strarray));
		$this->assertSame('foo', $strarray[0]);
		$this->assertSame('bar', $strarray[1]);
	}

	private function createArray(): git_strarray
	{
		$dir = $this->mkdir($this->getName());
		git::repository_init($repo, $dir, false);
		git::repository_index($index, $repo);
		git::index_write_tree($treeId, $index);
		git::tree_lookup($tree, $repo, $treeId);
		git::signature_new($sig, 'John Doe', 'john.doe@example.com', 1640263000, 60);
		git::commit_create_v($id, $repo, 'HEAD', $sig, $sig, null, 'Hello world!', $tree);
		git::commit_lookup($commit, $repo, $id);
		git::tag_create($oid1, $repo, 'v1.0', $commit, $sig, '', false);
		git::tag_create($oid2, $repo, 'v1.1.0', $commit, $sig, '', false);
		git::tag_create($oid3, $repo, 'v1.1.1', $commit, $sig, '', false);
		git::tag_list($array, $repo);
		return $array;
	}

}