<?php

namespace Shm\ShmUtils\ShmDoctor\ClassGenerator;

use Aws\Arn\Arn;
use Nette\PhpGenerator\ClassType;
use Shm\ShmTypes\ArrayOfType;

use Shm\ShmTypes\EnumType;
use Shm\ShmTypes\StructureType;
use Shm\ShmUtils\ShmDoctor\Utils\CodeGenerator;
use Shm\ShmUtils\ShmInit;

class AdminDescriptionGenerator
{
    /**
     * Generate admin lang classes for all structures
     */
    public static function generateAll(): void
    {
        $structures = \Shm\ShmUtils\ShmDoctor\Utils\StructureHelper::getStructures();

        foreach ($structures as $structure) {
            echo $structure::class . PHP_EOL;
            self::generate($structure::structure());
        }
    }

    /**
     * Generate admin lang class for a structure
     */
    public static function generate(StructureType $structure): void
    {
        $structure->updateKeys();
        $structure->updatePath();
        $dir = ShmInit::$rootDir . '/config/structures/';

        if (!is_dir($dir)) {
            mkdir($dir, 0777, true);
        }


        $fileName = $structure->collection . '.json';



        if (file_exists($dir . $fileName)) {
            $existData = json_decode(file_get_contents($dir . $fileName), true);
        } else {
            $existData = [];
        }



        $fields = self::generateFields($structure, $existData['schema'] ?? []);



        $result = [
            'schema' => $fields,
        ];

        file_put_contents($dir . $fileName, json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    }



    /**
     * Add constants to class based on structure for admin descriptions
     */
    private static function generateFields(StructureType $structure, array $existData): array
    {

        $result = [];

        foreach ($structure->items as $_key => $item) {
            if ($_key == '*') {
                continue;
            }



            if (!$item->inAdmin) {
                continue;
            }


            if ($item instanceof ArrayOfType) {
                $key =  $item->itemType->getPathString([], true);
            } else {

                $key =  $item->getPathString([], true);
            }


            $result[$key] = [
                'title' => $item->title ?? "",
                'description' => $existData[$key]['description'] ?? ""
            ];



            if ($item instanceof StructureType) {

                if (!$item->compositeType) {

                    $result = [...$result, ...self::generateFields($item, $existData ?? [])];
                }
            }

            if ($item instanceof ArrayOfType && $item->itemType instanceof StructureType) {

                if (!$item->itemType->compositeType) {
                    $result = [...$result, ...self::generateFields($item->itemType, $existData ?? [])];
                }
            }
        }

        return $result;
    }
}