<?php

namespace apexl\Io\modules\userDisplay\controllers;

use apexl\Io\includes\Controller;
use apexl\Io\includes\Routes;
use apexl\Io\includes\System;
use apexl\Io\modules\display\components\EntityDisplayTable;
use apexl\Io\modules\display\components\FormComponent;
use apexl\Io\modules\display\components\genericComponents;
use apexl\Io\modules\display\includes\Forms;
use apexl\Io\modules\display\services\Render;
use apexl\Io\modules\formbuilder\includes\checkboxField;
use apexl\Io\modules\user\entities\roleEntity;
use apexl\Io\modules\user\services\Permissions;
use apexl\Io\modules\userDisplay\callbacks\tableRowAlters;
use apexl\Io\modules\userDisplay\components\dashboardTiles;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

class rolesController extends Controller
{
    protected $permissions;
    protected $render;

    public function __construct(Render $render, Permissions $permissions)
    {
        parent::__construct();
        $this->permissions = $permissions;
        $this->render = $render;
    }


    /**
     * View the roleDisplay.
     * @return Response
     */
    public function view(Request $request, Response $response, $args)
    {
        $rowWrapper = genericComponents::rowWrapper('manageForm-wrapper col-sm-12');
        $rowWrapper->addComponent(dashboardTiles::roleViewTile($args['id']));

        $this->output::addResponse($request, $this->render::build([$rowWrapper]));
        return System::asJson($response);
    }

    /**
     * List roles.
     * @param $args
     * @return Response
     */
    public function roleList(Request $request, Response $response)
    {
        $this->output::addResponse($request, $this->render::build([(new EntityDisplayTable(new roleEntity()))->addCommonButtons()]));
        return System::asJson($response);
    }

    public function create(Request $request, Response $response, $args)
    {
        $title = 'Create new role';
        if ($id = $args['id'] ?? false) {
            $role = new roleEntity();
            $role->load($id);
            $title = 'Update ' . $role->name;
        }

        $form = (new FormComponent())->setID('roleCreate')->src(Routes::getRoutePattern('role.display.forms.createUpdate', $args));
        $this->render::setPageTitle($title);
        $this->output::addResponse($request, $this->render::build([genericComponents::dashboardBlockWrapper([$form])]));
        return System::asJson($response);
    }

    /**
     * @param $args
     * @return Response
     * @throws \Exception
     */
    public function manageForm(Request $request, Response $response, $args)
    {
        $roleEntity = new roleEntity();
        $form = Forms::entityForm($roleEntity, $args)->deleteField("permissions");

        $permissions = $this->permissions->getPermissions();
        foreach ($permissions as $macName => $data) {
            $form->setFieldsetSetting($data->group, 'fieldset_legend', $data->group);
            $form->setFieldsetSetting($data->group, 'fieldset_classes', 'row');

            $permissionBox = (new checkboxField($macName))->setLabel($data->name);
            if (isset($args[$roleEntity->primaryKey])) {
                $roleEntity->load($args[$roleEntity->primaryKey]);
                if (in_array($macName, $roleEntity->permissions)) {
                    $permissionBox->setValue($macName);
                }
            }
            $form->addField($permissionBox, $data->group);
        }
        $this->output::addResponse($request, $form->getBuiltFormArray());
        return System::asJson($response);
    }

    /**
     * @param array $args
     * @return Response
     */
    public function updateView(Request $request, Response $response, $args = [])
    {
        $form = (new FormComponent())->setID('roleCreate')->src(Routes::getRoutePattern('role.display.forms.createUpdate', $args));
        $this->output::addResponse($request, $this->render::build($form));
        return System::asJson($response);
    }

    public function roleSummery(Request $request, Response $response, $args)
    {
        $structure = [
            'tableHeader' => [
                'Role ID',
                'Role Name',
                'Role Created',
                'Role Created By',
                'permissions',
            ],
            'fields' => [
                'id',
                'name',
                'created',
                'created_by',
                'permissions',
            ],
            'callables' => [
                'field__created' => function ($key, $entityId, $row) {
                    return \apexl\Io\modules\userDisplay\callbacks\tableRowAlters::roleShortTable($key, $entityId, $row);
                },
                'field__created_by' => function ($key, $entityId, $row) {
                    return \apexl\Io\modules\userDisplay\callbacks\tableRowAlters::roleShortTable($key, $entityId, $row);
                },
                'field__permissions' => function ($key, $entityId, $row) {
                    return \apexl\Io\modules\userDisplay\callbacks\tableRowAlters::roleShortTable($key, $entityId, $row);
                }
            ]
        ];
        return $this->getEntityData($request, $response, $args, (new roleEntity()), [], $structure);
    }
}
