<?php

namespace Ignite\Core\Http\ViewComposers;

use Illuminate\Contracts\View\View;
use Ignite\Core\Contracts\Repositories\ImportRepository;

class ImportForm
{
    /**
     * @var ImportRepository
     */
    private $importRepository;

    /**
     * ImportForm constructor.
     *
     * @param  ImportRepository  $importRepository
     */
    public function __construct(ImportRepository $importRepository)
    {
        $this->importRepository = $importRepository;
    }

    /**
     * Bind data to the view.
     *
     * @param  View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('allowedTypes', $this->importRepository->getAllowedTypes());
        if (class_exists(\Ignite\Activity\Entities\Type::class)) {
            $vew = $view->with('activityTypes', \Ignite\Activity\Entities\Type::all())
                ->with('activityTypeStatuses', $this->getActivityTypeStatuses());
        }
    }

    /**
     * Return an array of Activity statuses used by the State Machine
     *
     * @return array
     */
    public function getActivityTypeStatuses()
    {
        if (!config('activity')) {
            return [];
        }

        $schema = config('activity.schema');
        $statuses = [];
        if (config()->has('activity.schema')) {
            foreach ($schema as $name => $filename) {
                $settings = $this->getSchema($this->getSetupFile($filename));
                $statuses[$name] = collect($settings['statuses']['states'])->keys()->toArray();
            }
        }

        return $statuses;
    }

    /**
     * Return filepath of the Activity Type json file
     * @param $filename
     *
     * @return string
     */
    private function getSetupFile($filename)
    {
        $activeTheme = resolve(\Ignite\Theme\Manager::class)->current();

        return $activeTheme->path().DIRECTORY_SEPARATOR.$filename;
    }

    /**
     * Return the schema of the specified Activity Type json file
     * @param  string  $filename
     * @return mixed
     */
    private function getSchema(string $filename)
    {
        $json = file_get_contents($filename);

        $data = json_decode($json, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new Exception(sprintf(
                'Unable to parse json for schema: %s.',
                json_last_error_msg()
            ));
        }

        return $data;
    }
}
