<?php

namespace Ignite\Core\Models\Form;

use Exception;
use Illuminate\Support\Arr;

class CoreForm extends Form
{
    use GroupByTableTrait;

    /**
     * The schema resolver.
     *
     * @var ThemeSchemaResolver
     */
    protected $schemaResolver;

    /**
     * Form constructor.
     *
     * @param ThemeSchemaResolver $schemaResolver
     */
    public function __construct(ThemeSchemaResolver $schemaResolver)
    {
        $this->schemaResolver = $schemaResolver;
    }

    /**
     * Build the form from the JSON schema file.
     *
     * @param string $type
     * @param bool $renderGroups
     *
     * @throws Exception
     */
    protected function buildFromSchema($type, bool $renderGroups = false)
    {
        $this->setFormOption('class', 'form-horizontal');

        $schema = $this->getSchema($type);

        foreach ($schema['fields'] as $field) {
            if ($this->shouldGroupByTable($field)) {
                $this->extractGroup($field);
                continue;
            }

            $this->renderField($field);
        }

        if (method_exists($this, 'renderGroups') && $renderGroups) {
            $this->renderGroups($schema);
        }
    }

    /**
     * Get the schema from the JSON file.
     *
     * @param string $type
     *
     * @return array
     * @throws Exception
     */
    protected function getSchema(string $type)
    {
        return $this->schemaResolver->resolve($type);
    }

    /**
     * Determine whether the given form schema should group fields by their assigned table.
     *
     * @param array $field
     *
     * @return bool
     */
    protected function shouldGroupByTable(array $field)
    {
        return Arr::has($field, 'group') &&
            method_exists($this, 'extractGroup') &&
            property_exists($this, 'groupByTable') &&
            $this->groupByTable;
    }
}
