<?php
/*
 * Fusio
 * A web-application to create dynamically RESTful APIs
 *
 * Copyright (C) 2015-2020 Christoph Kappestein <christoph.kappestein@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace Fusio\Cli\Deploy;

use RuntimeException;
use Symfony\Component\Yaml\Tag\TaggedValue;

/**
 * NameGenerator
 *
 * @author  Christoph Kappestein <christoph.kappestein@gmail.com>
 * @license http://www.gnu.org/licenses/agpl-3.0
 * @link    http://fusio-project.org
 */
class NameGenerator
{
    public static function getActionNameFromSource($source)
    {
        if (is_string($source)) {
            // remove scheme if uri format
            if (($pos = strpos($source, '://')) !== false) {
                $source = substr($source, $pos + 3);
            }

            if (is_file($source)) {
                $pos = (int) strpos($source, DIRECTORY_SEPARATOR . 'src');
                $source = realpath($source);
                $source = substr($source, $pos + 4);
            }

            return preg_replace('/[^a-zA-Z0-9\-\_]/', '_', $source);
        } else {
            throw new RuntimeException('Invalid action source');
        }
    }

    public static function getSchemaNameFromSource($source)
    {
        if ($source instanceof TaggedValue) {
            if ($source->getTag() === 'include') {
                $source = trim($source->getValue());
                $source = str_replace('\\', '/', $source);
                $source = str_replace('resources/schema/', '', $source);
                $source = str_replace('.json', '', $source);
                $source = str_replace(' ', '-', ucwords(str_replace('/', ' ', $source)));

                return $source;
            } else {
                throw new RuntimeException('Invalid tag provide: ' . $source->getTag());
            }
        } elseif (is_string($source)) {
            if (preg_match('/^[a-zA-Z0-9\-\_]{3,255}$/', $source)) {
                return $source;
            } else {
                return self::getNameFromSchema($source);
            }
        } elseif (is_array($source)) {
            return self::getNameFromSchema(json_encode($source));
        } else {
            throw new RuntimeException('Schema should be a string containing an "!include" directive pointing to a JsonSchema file');
        }
    }

    private static function getNameFromSchema(string $schema)
    {
        if (preg_match('/^[a-zA-Z0-9_\\\]+$/', $schema)) {
            if (class_exists($schema)) {
                return preg_replace('/[^a-zA-Z0-9\-\_]/', '_', $schema);
            } else {
                throw new RuntimeException('Provided class "' . $schema . '" does not exist');
            }
        } else {
            $data = json_decode($schema);
            if (!$data instanceof \stdClass) {
                throw new RuntimeException('Schema must be a valid json schema');
            }

            if (isset($data->{'$ref'}) && is_string($data->{'$ref'})) {
                return preg_replace('/[^A-z0-9\-\_]/', '_', $data->{'$ref'});
            } elseif (isset($data->title) && is_string($data->title)) {
                return preg_replace('/[^A-z0-9\-\_]/', '_', $data->title);
            }

            // at last fallback we can only use the md5 of the schema as name
            return 'Schema-' . substr(md5($schema), 0, 8);
        }
    }
}
