<?php

/**
 *
 * @OA\Tag(
 *   name="lokalize",
 *   description="Lokalize module",
 * )
 */

$this->on('restApi.config', function($restApi) {

    /**
     * @OA\Get(
     *     path="/lokalize/project/{name}",
     *     tags={"lokalize"},
     *     @OA\Parameter(
     *         description="Project name",
     *         in="path",
     *         name="name",
     *         required=true,
     *         @OA\Schema(type="string")
     *     ),
     *    @OA\Parameter(
     *         description="Return only specified locale",
     *         in="query",
     *         name="locale",
     *         required=false,
     *         @OA\Schema(type="string")
     *     ),
     *     @OA\Parameter(
     *         description="Namespace dotted keys",
     *         in="query",
     *         name="nested",
     *         required=false,
     *         @OA\Schema(type="integer")
     *     ),
     *     @OA\Response(response="200", description="Language strings as JSON", @OA\JsonContent()),
     *     @OA\Response(response="404", description="Project not found")
     * )
     */

    $restApi->addEndPoint('/lokalize/project/{name}', [
        'GET' => function($params, $app) {

            $name = $params['name'];

            $project = $app->module('lokalize')->project($name);

            if (!$project) {
                $app->response->status = 404;
                return ["error" => "Project <{$name}> not found"];
            }

            if (!$app->helper('acl')->isAllowed('lokalize/api/read', $app->helper('auth')->getUser('role'))) {
                $app->response->status = 403;
                return ['error' => 'Permission denied'];
            }

            $values = new \ArrayObject(isset($project['values']) ? $project['values'] : []);

            foreach ($project['locales'] as $locale) {

                if (!isset($values[$locale['i18n']]))  {
                    $values[$locale['i18n']] = new \ArrayObject([]);
                }

                foreach ($project['keys'] as $key) {

                    if (!isset($key['name']) || !$key['name']) continue;

                    if (isset($key['plural']) && $key['plural']) {
                        if (!isset($values[$locale['i18n']][$key['name']]['plural'])) {
                            $values[$locale['i18n']][$key['name'].'_plural'] = null;
                        } else {
                            $values[$locale['i18n']][$key['name'].'_plural'] = $values[$locale['i18n']][$key['name']]['plural'] ?? null;
                        }
                    }

                    if (!isset($values[$locale['i18n']][$key['name']])) {
                        $values[$locale['i18n']][$key['name']] = null;
                    } else {
                        $values[$locale['i18n']][$key['name']] = $values[$locale['i18n']][$key['name']]['value'] ?? null;
                    }
                }
            }

            if ($app->param('nested:int')) {

                $resolveNested = function($obj) {

                    foreach (array_keys((array)$obj) as $key) {
                        if (\str_contains($key, '.')) {
                            $val = $obj[$key];
                            $parts = explode('.', $key, 2);

                            if (!isset($obj[$parts[0]]) || !\is_array($obj[$parts[0]])) {
                                $obj[$parts[0]] = [];
                            }

                            $obj[$parts[0]][$parts[1]] = $val;
                            unset($obj[$key]);
                        }
                    }

                    return $obj;
                };

                foreach (array_keys((array)$values) as $key) {
                    $values[$key] = $resolveNested($values[$key]);
                }
            }

            $locale = $app->param('locale');

            return $locale ? ($values[$locale] ?? false): $values;
        }
    ]);
});


$this->on('graphql.config', function($gql) {
    $app = $this;
    include(__DIR__.'/graphql/lokalize.php');
});
