<?php

namespace Shm\ShmRPC\ShmRPCCodeGen\CodeGenPhp;

use Shm\ShmTypes\BaseType;
use Shm\ShmTypes\StructureType;
use Shm\ShmUtils\ShmInit;
use Nette\PhpGenerator\PhpFile;
use Shm\ShmTypes\EnumType;

class CodeGenPhp
{


    private static $baseEndpoint = '';
    private static $dirFiles = '';
    private static $globalNamespace = 'App\\ApiClient';


    public static function getClassName(string $key): string
    {
        return ucfirst($key) . 'Request';
    }







    public static function php(array $schema)
    {



        $REQUEST_URI = $_SERVER['REQUEST_URI'];

        //Убарем GET параметры
        $url = explode('?', $REQUEST_URI)[0];
        $host = $_SERVER['HTTP_HOST'];
        self::$baseEndpoint = 'http://' . $host . $url;



        self::$dirFiles =  ShmInit::$rootDir . '/app/ApiClient/';
        if (!is_dir(self::$dirFiles)) {
            mkdir(self::$dirFiles, 0777, true);
        }


        //Отчищаем папку от всех файлов и директорий
        $files = glob(self::$dirFiles . '*.*');
        foreach ($files as $file) {
            unlink($file);
        }



        $class = new \Nette\PhpGenerator\ClassType('ApiClient');

        $useImportNamespaces = [];

        foreach ($schema as $key => $field) {

            $className = self::getClassName($key);


            $createRequestClass = new CreateRequestClass(self::$globalNamespace . '\\' . ucfirst($key), self::$dirFiles . ucfirst($key) . '/', $className, $key);
            $createRequestClass->create($field);

            $useImportNamespaces[] = 'use ' . self::$globalNamespace . '\\' . ucfirst($key) . '\\' . $className . ';';

            //Добалвяем функкции пустые по $key
            $method = $class->addMethod($key);
            $method->setVisibility('public');
            //static
            $method->setStatic();
            $method->setReturnType($className);
            $method->setBody('return new ' . $className . '();');
        }


        $class->addProperty('headers')->setType('array')->setValue([])->setVisibility('private')->setStatic();
        //private static $endpoint =
        $class->addProperty('endpoint')->setType('string')->setValue(self::$baseEndpoint)->setVisibility('private')->setStatic();
        //private static $token
        $class->addProperty('token')->setType('string')->setValue("")->setVisibility('private')->setStatic();
        //private static $apiKey = '';
        $class->addProperty('apiKey')->setType('string')->setValue("")->setVisibility('private')->setStatic();

        //public function endpoint(string $endpoint): void
        $class->addMethod('endpoint')->setReturnType('void')->setBody('self::$endpoint = $endpoint;')->setVisibility('public')->setStatic()->addParameter('endpoint')->setType('string');
        //public function token(string $token): void
        $class->addMethod('token')->setReturnType('void')->setBody('self::$token = $token;')->setVisibility('public')->setStatic()->addParameter('token')->setType('string');
        //public function apiKey(string $apiKey): void
        $class->addMethod('apiKey')->setReturnType('void')->setBody('self::$apiKey = $apiKey;')->setVisibility('public')->setStatic()->addParameter('apiKey')->setType('string');

        $class->addMethod('headers')->setReturnType('void')->setBody('self::$headers = $headers;')->setVisibility('public')->setStatic()->addParameter('headers')->setType('array');


        $sendRequestMethodBodyPath = __DIR__ . '/sendRequest.tpl';
        $sendRequestMethodBody = file_get_contents($sendRequestMethodBodyPath);


        $sendRequestMethod = $class->addMethod('_sendRequest');
        $sendRequestMethod->setStatic();
        $sendRequestMethod->setReturnType('array');
        $sendRequestMethod->addParameter('method')->setType('string');
        $sendRequestMethod->addParameter('params')->setType('array')->setDefaultValue([]);
        $sendRequestMethod->addParameter('extensions')->setType('array')->setDefaultValue([]);
        $sendRequestMethod->setBody($sendRequestMethodBody);


        $output = "<?php\n\n"; // заголовок файла
        $output .= "namespace " . self::$globalNamespace . ";\n";

        $output .= implode("\n", $useImportNamespaces) . "\n\n";

        $output .= $class . "\n\n"; // собираем все классы

        $filePath = self::$dirFiles . 'ApiClient.php';
        file_put_contents($filePath, $output);



        exit;
    }
}