<?php

namespace Velis\Test\Mvc\View\Helper;

use PHPUnit\Framework\TestCase;
use Velis\Bpm\Ticket\Post;
use Velis\Bpm\Ticket\Post\Checklist\Item;
use Velis\Mvc\View\Helper\Checklist;

/**
 * @author Jan Małysiak <jan.malysiak@velis.pl>
 */
class ChecklistTest extends TestCase
{
    /**
     * @var Item[][]
     */
    private static $itemMap = [];

    /**
     * @param array $itemMap
     * @param Post $post
     * @param string $expectedOutput
     *
     * @dataProvider provideTestData
     */
    public function testInvoke(array $itemMap, Post $post, string $expectedOutput)
    {
        self::$itemMap = $itemMap;

        $helper = new Checklist();
        $actualOutput = $helper($post);

        $this->assertEquals($expectedOutput, $actualOutput);
    }

    public function provideTestData()
    {
        return [
            $this->createSingleItemDataSet('first item'),
            $this->createSingleItemDataSet('<tag>', '&lt;tag&gt;'),
            $this->createSingleItemDataSet('@<tag>@', '<code>&lt;tag&gt;</code>'),
        ];
    }

    private function createSingleItemDataSet($itemContent, $renderedContent = null)
    {
        if (null === $renderedContent) {
            $renderedContent = $itemContent;
        }

        $itemMock = $this->createMock(Item::class);

        $itemId = 1;
        $itemMock->method('id')
            ->willReturn($itemId);

        $itemMock->method('getName')
            ->willReturn($itemContent);

        $itemMap = [
            0 => [
                $itemMock,
            ],
        ];

        $postMock = $this->createMock(Post::class);

        $postId = 123;
        $postMock->method('id')
            ->willReturn($postId);

        $postMock->method('getChecklistItemsByParentId')
            ->willReturnCallback([$this, 'mockGetChecklistItemsByParentId']);

        $output = '<div class="checklist" id="checklist' . $postId . '" data-id="' . $postId . '">'
            . '<div data-dojo-type="dijit/ProgressBar" id="checklistProgressBar' . $postId . '"></div>'
            . '<ol><li class="item' . $itemId . ' checklistLeaf"><div style="margin-bottom: 3px" class="checklist-title">'
            . '<input type="checkbox" class="cbx" id="chl' . $itemId . '" data-id="' . $itemId . '" data-dojo-type="dijit/form/CheckBox">'
            . '&nbsp;' . $renderedContent . '</div></li></ol></div>';

        return [
            $itemMap,
            $postMock,
            $output,
        ];
    }

    public function mockGetChecklistItemsByParentId($parentId = null)
    {
        if (null === $parentId) {
            return self::$itemMap[0];
        }

        if (array_key_exists($parentId, self::$itemMap)) {
            return self::$itemMap[$parentId];
        }
    }
}
