<?php

namespace frontend\urls;

use core\entities\post\Post;
use core\entities\post\PostType;
use core\repositories\post\read\PostReadRepository;
use core\repositories\post\read\PostTypeReadRepository;
use yii\base\BaseObject;
use yii\base\InvalidParamException;
use yii\caching\Cache;
use yii\web\UrlNormalizerRedirectException;
use yii\web\UrlRuleInterface;

class PostMainUrlRule extends BaseObject implements UrlRuleInterface
{
	public $prefix = 'post';

    private $repository;
    private $cache;

    public function __construct(PostTypeReadRepository $repository, Cache $cache, $config = [])
    {
        parent::__construct($config);
        $this->repository = $repository;
        $this->cache = $cache;
    }

    public function parseRequest($manager, $request)
    {
	    $path = $request->pathInfo;
	    //if (preg_match('#^' . $this->prefix . '/(.*[a-z])$#is', $request->pathInfo, $matches)) {
		//    $path = $matches['1'];

		    $result = $this->cache->getOrSet( [ 'post_main_route', 'path' => $path ], function () use ( $path ) {
			    if ( ! $type = $this->repository->findByName( $this->getPathName( $path ) ) ) {
				    return [ 'tid' => null, 'path' => null ];
			    }

			    return [ 'tid' => $type->id, 'path' => $this->getPagePath( $type ) ];
		    }, 1000 );

		    if ( empty( $result['tid'] ) ) {
			    return false;
		    }

		    if ( $path != $result['path'] ) {
			    throw new UrlNormalizerRedirectException( [ 'post/index', 'tid' => $result['tid'] ], 301 );
		    }

		    //print_r($path); die;
		    return [ 'post/index', [ 'tid' => $result['tid'] ] ];
	    //}
	    //return false;
    }

    public function createUrl($manager, $route, $params)
    {
        if ($route == 'post/index') {
            if (empty($params['tid'])) {
                throw new InvalidParamException('Empty type.');
            }
            $tid = $params['tid'];

            $url = $this->cache->getOrSet(['post_main_route', 'tid' => $tid], function () use ($tid) {
                if (!$type = $this->repository->find($tid)) {
                    return null;
                }
                return $this->getPagePath($type);
            });

            if (!$url) {
                throw new InvalidParamException('Undefined id.');
            }

            unset($params['tid']);
            if (!empty($params) && ($query = http_build_query($params)) !== '') {
                $url .= '?' . $query;
            }
            return $url;
        }
        return false;
    }

    private function getPathName($path): string
    {
        $chunks = explode('/', $path);
        return end($chunks);
    }

    private function getPagePath(PostType $type): string
    {
    	$chunks = ['post', $type->name];
        return implode('/', $chunks);
    }
}