<?php

namespace Diamond\Repositories\ChangeLog;

use QueryBuilder\SearchCriteria;
use Repo\CollectionInterface;
use Repo\Concrete\AbstractCrudRepository;
use Repo\PaginationInterface;
use Diamond\Domain\ChangeLog\ChangeLogEntity;
use Diamond\Domain\ChangeLog\ChangeLogCollection;

class ChangeLogRepository extends AbstractCrudRepository implements \Repo\CrudRepositoryInterface
{
    public function buildEntityFromArray(array $row): \Repo\EntityInterface
    {
        return
            self::createEntity()
                ->setId($row['id'])
                ->setFileName($row['filename'])
                ->setSize($row['size'])
                ->setDate($row['datetime'])
                ->setPathName($row['pathname']);
    }

    

    /**
     * @return \Repo\EntityInterface|ErrorLogEntity
     */
    public static function createEntity(): \Repo\EntityInterface
    {
        return new ChangeLogEntity();
    }


    public function save(\Repo\EntityInterface $entity): void
    {
        // TODO: Implement save() method.
    }

    /**
     * @param PaginationInterface $criteria
     * @return CollectionInterface
     * @throws \Repo\Concrete\Exceptions\Collection
     */
    public function findByCriteria(PaginationInterface $criteria): CollectionInterface
    {

        $res = str_replace(["\r\n", "\n"], '', file_get_contents(__DIR__ . '/../../../../changelog.md'));
        $data = [];
        $collection = new ChangeLogCollection();

        if (preg_match_all("~(##[\s]?(\d{4}\-\d{2}\-\d{2})###.*?Added(([-\s\na-zA-Zа-яА-Я0-9.,]+)))~iu", $res, $matches)) {
            $i = 1;
            foreach ($matches[3] as $k => $v) {

                if (preg_match_all("~\-(([\s\na-zA-Zа-яА-Я0-9.,].*?)\.([\s\na-zA-Zа-яА-Я0-9.,]+))~iu", $v, $m)) {

                    foreach ($m[2] as $k2 => $v2) {
                        $title = trim($v2);
                        $desc = trim($m[3][$k2]);
                        $date = $matches[2][$k];


                        $collection->push(
                            (new ChangeLogEntity())
                                ->setDate(\DateTime::createFromFormat('Y-m-d', $date))
                                ->setTitle($title)
                                ->setDesc($desc)
                                ->setId($i)
                        );

                        $i++;

                    }


                }
                if ($criteria->getLimit() > 0 && $collection->count() >= $criteria->getLimit()) {
                    break;
                }
            }

        }


        return $collection;
    }

    protected function modifyCriteria(PaginationInterface $criteria, SearchCriteria $dbCriteria): void
    {
        // TODO: Implement modifyCriteria() method.
    }


}