<?php

namespace Shm\ShmAdmin\AdminRPC;

use Shm\Shm;
use Shm\ShmAdmin\AdminPanel;
use Shm\ShmAdmin\Types\BaseStructureType;
use Shm\ShmAuth\Auth;
use Shm\ShmDB\mDB;
use Shm\ShmRPC\ShmRPC;

use Shm\ShmTypes\IDsType;
use Shm\ShmTypes\IDType;
use Shm\ShmTypes\StructureType;
use Shm\ShmUtils\LuIcons;

class AdminRPCCollection
{


    public static function getCollectionMenu($structure)
    {



        $groups = [];

        $groupStack = [];

        $allItems = [];

        foreach ($structure->items as $item) {


            if ($item->inAdmin) {

                $group = [
                    'key' => $item->group['key'] ?? null,
                    'group' => $item->group['key'] ?? null,
                    'icon' => $item->group['icon'] ?? LuIcons::Folder(),
                    'title' => $item->group['title'] ?? null,
                ];
                if ($item->group['key'] == 'default') {
                    $group['title'] = "Общее";
                }


                if (!in_array($group['key'], $groupStack)) {
                    $groupStack[] = $group['key'];
                }

                $groups[$group['key']] = $group;
            }
        }



        $children = [];

        if (in_array('default', $groupStack)) {
            $children[] = $groups['default'];
        }


        foreach ($groupStack as $groupKey) {

            if ($groupKey == 'default') {
                continue;
            }

            $children[] = $groups[$groupKey];
        }


        return [

            'menu' => [[
                'key' => 'content',
                'title' => 'Контент',
                'children' => $children,
            ]],
            'allItems' => $children,
        ];
    }

    public static function rpc()
    {

        return ShmRPC::lazy(function () {




            $typeCollectionMenu =   Shm::structure([
                'menu' => Shm::arrayOf(Shm::structure([
                    'key' => Shm::string(),
                    'icon' => Shm::string(),
                    'title' => Shm::string(),
                    'group' => Shm::string(),
                    'children' => Shm::arrayOf(Shm::structure([
                        'key' => Shm::string(),
                        'icon' => Shm::string(),
                        'title' => Shm::string(),
                        'group' => Shm::string(),
                    ])),
                ])),
                'allItems' => Shm::arrayOf(Shm::structure([
                    'key' => Shm::string(),
                    'icon' => Shm::string(),
                    'title' => Shm::string(),
                    'group' => Shm::string(),
                ])),
            ]);

            return [
                'type' => Shm::structure([
                    'structureData' => Shm::structure([
                        "mainStructure" => BaseStructureType::get(),
                        "subStructure" => BaseStructureType::get(),
                    ]),

                    'collectionMenu' => $typeCollectionMenu,
                ]),
                'args' => Shm::structure([
                    "collection" => Shm::nonNull(Shm::string()),
                ]),
                'resolve' => function ($root, $args) {

                    Auth::authenticateOrThrow(...AdminPanel::$authStructures);

                    if (!isset($args['collection'])) {
                        return [
                            'structureData' => null,
                            'descriptions' => null,

                        ];
                    }

                    $mainStructure = AdminPanel::fullSchema()->findItemByCollection($args['collection'], true);
                    $subStructure = null;
                    if (! $mainStructure) {
                        $subStructure = AdminPanel::fullSchema()->findItemByCollection($args['collection']);
                    }

                    if (!$mainStructure && !$subStructure) {
                        return [
                            'structureData' => [
                                "mainStructure" => null,
                                "subStructure" => null,
                            ],
                            'descriptions' => null,

                        ];
                    }

                    $structure = $mainStructure ?? $subStructure;

                    return [
                        'structureData' => [
                            "mainStructure" => $mainStructure?->json(),
                            "subStructure" => $subStructure?->json(),
                        ],
                        'collectionMenu' => self::getCollectionMenu($structure),
                    ];
                }

            ];
        });
    }

    public static function rpcAccess()
    {
        return ShmRPC::lazy(function () {
            return [
                'type' => Shm::structure([
                    'canCreate' => Shm::boolean(),
                    'canUpdate' => Shm::boolean(),
                    'canDelete' => Shm::boolean(),
                    'canExport' => Shm::boolean(),
                    'buttons' => Shm::structure([
                        'showSaveButton' => Shm::boolean(),
                        'showCreateButton' => Shm::boolean(),
                        'showDeleteButton' => Shm::boolean(),
                        'showActionButton' => Shm::boolean(),
                        'showRelationButton' => Shm::boolean(),
                        'showCloneButton' => Shm::boolean(),
                        'showCopyButton' => Shm::boolean(),
                    ])->staticBaseTypeName("AccessButtons"),
                ])->staticBaseTypeName("CollectionAccess"),
                'args' => Shm::structure([
                    "collection" => Shm::nonNull(Shm::string()),
                    "ids" => Shm::arrayOf(Shm::string()),
                ]),
                'resolve' => function ($root, $args) {
                    Auth::authenticateOrThrow(...AdminPanel::$authStructures);

                    if (!isset($args['collection'])) {
                        return null;
                    }

                    $structure = AdminPanel::fullSchema()->findItemByCollection($args['collection']);


                    if (!$structure) {
                        return null;
                    }

                    $ids = $args['ids'] ?? [];
                    $ids = array_map(function ($id) {
                        return mDB::id($id);
                    }, $ids);

                    $isSingle = $structure->single;


                    $canCreate = !$isSingle ? $structure->getCanCreate() : false;
                    $canUpdate = $structure->getCanUpdate($ids);
                    $canDelete = !$isSingle ? $structure->getCanDelete($ids) : false;

                    $canExport = !$isSingle ? $structure->getCanExport() : false;

                    $showSaveButton = false;

                    if (count($ids) > 0) {
                        $showSaveButton = $canUpdate;
                    } else {
                        $showSaveButton = $canCreate;
                    }


                    $showCreateButton = !$isSingle ? $canCreate : false;




                    $showDeleteButton = false;
                    if (count($ids) > 0) {
                        $showDeleteButton = $canDelete;
                    } else {
                        $showDeleteButton = false;
                    }

                    $showActionButton = false;
                    if (count($ids) > 0) {
                        $showActionButton = true;
                    }


                    $showRelationButton = false;
                    if (count($ids) > 0 && !$isSingle) {
                        $showRelationButton = true;
                    }






                    $showCloneButton = false;
                    if (!$isSingle && $canCreate && count($ids) > 0) {
                        $showCloneButton = true;
                    }



                    $showCopyButton = false;
                    if (!$isSingle && count($ids) > 0) {
                        $showCopyButton = true;
                    }


                    return [
                        'canCreate' => $canCreate,
                        'canUpdate' => $canUpdate,
                        'canDelete' => $canDelete,
                        'canExport' => $canExport,
                        'buttons' => [
                            'showSaveButton' => $showSaveButton,
                            'showCreateButton' => $showCreateButton,
                            'showDeleteButton' => $showDeleteButton,
                            'showActionButton' => $showActionButton,
                            'showRelationButton' => $showRelationButton,
                            'showCloneButton' => $showCloneButton,
                            'showCopyButton' => $showCopyButton,
                        ]
                    ];
                }
            ];
        });
    }

    public static function rpcRelations()
    {

        return ShmRPC::lazy(function () {


            $relationType = Shm::structure([
                'icon' => Shm::string(),
                'title' => Shm::string(),
                'subtitle' => Shm::string(),
                'collection' => Shm::string(),
                'key' => Shm::string(),
            ])->staticBaseTypeName("CollectionRelation");


            return [
                'type' =>  Shm::arrayOf($relationType),

                'args' => Shm::structure([
                    "collection" => Shm::nonNull(Shm::string()),
                    /**
                     * TODO выводить только связанные разделы в которых есть данные для вывода
                     */
                    "ids" => Shm::arrayOf(Shm::string()),
                ]),
                'resolve' => function ($root, $args) {

                    Auth::authenticateOrThrow(...AdminPanel::$authStructures);

                    if (!isset($args['collection'])) {
                        return null;
                    }

                    $structure = AdminPanel::fullSchema()->findItemByCollection($args['collection']);


                    if (!$structure) {
                        return null;
                    }

                    $ids = $args['ids'] ?? [];
                    $ids = array_map(function ($id) {
                        return mDB::id($id);
                    }, $ids);

                    $collection = $structure->collection;
                    $fields = AdminPanel::fullSchema()->findIDTypeByCollection($collection);

                    $relations = [];
                    foreach ($fields as $field) {



                        if ($field instanceof IDsType || $field instanceof IDType) {

                            $rootParent = $field->getRootParent();
                            if ($rootParent instanceof StructureType) {

                                if ($rootParent?->collection == $collection) {
                                    continue;
                                }


                                if ($rootParent?->collection == 'subAccounts') {
                                    continue;
                                }


                                $fieldPath = $field->getPathString([], true);

                                if (!$fieldPath) {
                                    continue;
                                }


                                /*    if (count($ids) > 0) {


                                    //Проверям что есть данные 
                                    $existItem = $rootParent->findOne([

                                        $fieldPath => ['$in' => $ids]

                                    ]);

                                    if (!$existItem) {
                                        continue;
                                    }
                                }
                                */


                                //убираем .[] из ключа
                                $fieldPath = str_replace('.[]', '', $fieldPath);

                                $relationCollection = $rootParent?->collection;

                                $relations[$relationCollection . $fieldPath] = [
                                    'collection' => $rootParent?->collection,
                                    'key' =>  $fieldPath,

                                    'icon' => $rootParent->assets['icon'] ?? null,
                                    'title' => $rootParent->title,
                                    'subtitle' => $field->title,
                                ];
                            }
                        }
                    }
                    return $relations;
                }

            ];
        });
    }
}
