<?php

namespace Snaju\Inception\Route\Loaders\Twig\Extensions;

use App\Models\User;
use Snaju\Inception\Http\Message\FlashMessage;
use Snaju\Inception\InceptionCore;
use Snaju\Inception\Route\Loaders\Twig\TemplateManager;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Snaju\Inception\Settings\Config;

class CustomFunctions extends AbstractExtension
{

    public function getFunctions(): array
    {
        return array(
            new TwigFunction('public', [$this, 'getPublicFilePath']),
            new TwigFunction('publicDirName', [$this, 'getPublicDirectoryName']),
            new TwigFunction('config', [$this, 'getConfigValue']),
            new TwigFunction('env', [$this, 'getEnv']),
            new TwigFunction('getFlashMessage', [$this, 'getFlashMessage']),
            new TwigFunction('getFlashMessages', [$this, 'getFlashMessages']),
            new TwigFunction('getFullYear', [$this, 'getFullYear']),
            new TwigFunction('input', [$this, 'getInput'])
        );
    }

    public function getPublicFilePath(string $file): string
    {
        return "/" . Config::get('app.publicDirectory') . "/" . $file;
    }

    public function getPublicDirectoryName()
    {
        return Config::get('app.publicDirectory');
    }

    public function getConfigValue(string $key)
    {
        return Config::get($key);
    }

    public function getEnv(string $key): ?string
    {
        return env($key);
    }

    public function getFlashMessage($name): string
    {
        return flash()->get($name);
    }

    public function getFlashMessages(): array
    {
        return flash()->toArray();
    }

    public function getFullYear(): string
    {
        return date('Y');
    }

    public function getInput($key)
    {
        if (isset(TemplateManager::getAll()->inputs->{$key})) {
            return TemplateManager::getData("inputs.{$key}");
        }

        if (isset($_SESSION['inputs'][$key])) {
            $a = $_SESSION['inputs'][$key];
            $_SESSION['inputs'][$key] = null;
            unset($_SESSION['inputs'][$key]);

            return $a;
        }

        return "";
    }

}