<?php

namespace Ignite\Core\Models\Form;

use Exception;
use Ignite\Theme\Manager as ThemeManager;
use Ignite\Theme\Theme;

class ThemeSchemaResolver
{
    /**
     * @var ThemeManager
     */
    protected $themeManager;

    /**
     * @var string
     */
    protected $path;

    /**
     * ThemeSchemaResolver constructor.
     *
     * @param ThemeManager $themeManager
     * @param string|null $path
     */
    public function __construct(ThemeManager $themeManager, $path = null)
    {
        $this->themeManager = $themeManager;
        $this->path = $path;
    }

    /**
     * Resolve the schema for the given type.
     *
     * @param string $type
     *
     * @return array
     * @throws Exception
     */
    public function resolve($type)
    {
        return $this->parse($type, $this->getFilePath($type));
    }

    /**
     * The file path to the JSON schema file.
     *
     * @param string $type
     *
     * @return string
     */
    protected function getFilePath($type)
    {
        if (! is_null($this->path)) {
            return $this->path;
        }

        $themePath = $this->getActiveTheme()->path();

        return $themePath . DIRECTORY_SEPARATOR . 'forms' . DIRECTORY_SEPARATOR . $type . '.json';
    }

    /**
     * Parse the JSON schema file.
     *
     * @param string $type
     * @param string $path
     *
     * @return mixed
     * @throws Exception
     */
    protected function parse($type, $path)
    {
        $json = file_get_contents($path);
        $data = json_decode($json, true);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception("Unable to load schema for `$type` form. Error: " . json_last_error_msg());
        }

        return $data;
    }

    /**
     * The active theme.
     *
     * @return Theme
     */
    protected function getActiveTheme()
    {
        return $this->themeManager->current();
    }
}
