<?php

namespace idoit\Module\SyneticsAdmin\Controller;

use idoit\AddOn\Manager\Downloader;
use idoit\AddOn\Manager\ManagePackage;
use idoit\AddOn\Manager\ManageTenant;
use idoit\Component\FeatureManager\FeatureManager;
use idoit\Module\License\Entity\License;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * Addon controller
 *
 * @package   idoit\Module\Synetics_admin\Controller
 * @copyright synetics
 * @license   https://www.i-doit.com/
 */
class AddonController
{
    public function installAddon(Request $request): Response
    {
        global $g_license_token;

        $filename = BASE_DIR . 'temp/addon-' . substr(md5(microtime()), 0, 8) . '.zip';
        try {
            if (!\isys_auth_synetics_admin::instance()->canManageAddons() || FeatureManager::isCloud()) {
                return JSONResponseFactory::permissionError();
            }
            $database = \isys_application::instance()->container->get('database');
            $downloader = new Downloader();
            $body = $request->toArray();
            $identifier = $body['identifier'];
            $downloadLink = $body['downloadLink'];

            if (!$identifier || !$downloadLink) {
                return JSONResponseFactory::error("Unable to find add-on with identifier {$identifier}");
            }

            $downloader = new Downloader();
            $downloader->download($downloadLink, $filename);
            $package = new ManagePackage(\isys_application::instance()->app_path . 'src/classes/modules/');
            $package->load($filename);

            if (!$package->isAddonValid()) {
                return JSONResponseFactory::error('Invalid add-on structure.');
            };

            if (!$package->checkRequirements()) {
                return JSONResponseFactory::error('Requirements for add-on are not met.');
            }

            if (!$package->unpack()) {
                return JSONResponseFactory::error('Unable to unpack add-on.');
            }

            if (!$package->moveToaddonRootPath()) {
                return JSONResponseFactory::error('Unable to move add-on folder to i-doit.');
            }

            $tenantPackage = new ManageTenant($database, \isys_application::instance()->app_path . 'src/classes/modules/');
            $tenantPackage->setIdentifier($identifier);
            $tenantPackage->install();
            unlink($filename);

            return JSONResponseFactory::success();
        } catch (\Throwable $e) {
            unlink($filename);
            return JSONResponseFactory::error($e->getMessage());
        }
    }

    public function uninstallAddon(Request $request)
    {
        try {
            if (!\isys_auth_synetics_admin::instance()->canManageAddons() || FeatureManager::isCloud()) {
                return JSONResponseFactory::permissionError();
            }
            $database = \isys_application::instance()->container->get('database');
            /** @var \isys_module_manager $moduleManager */
            $moduleManager = \isys_application::instance()->container->get('moduleManager');
            $body = $request->toArray();
            $identifier = $body['identifier'];

            if (!$moduleManager->is_installed($identifier)) {
                return JSONResponseFactory::error('Add-on is not installed.');
            }
            $addon = new ManageTenant($database, \isys_application::instance()->app_path . 'src/classes/modules/');
            $addon->setIdentifier($identifier);
            if (!$addon->uninstall() || !$addon->deleteAddonFiles()) {
                return JSONResponseFactory::error('Uninstalling add-on failed.');
            }

            return JSONResponseFactory::success();
        } catch (\Throwable $e) {
            return JSONResponseFactory::error($e->getMessage());
        }
    }

    public function setAddonStatus(Request $request)
    {
        try {
            if (!\isys_auth_synetics_admin::instance()->canManageAddons() || FeatureManager::isCloud()) {
                return JSONResponseFactory::permissionError();
            }
            $database = \isys_application::instance()->container->get('database');
            /** @var \isys_module_manager $moduleManager */
            $moduleManager = \isys_application::instance()->container->get('moduleManager');
            $body = $request->toArray();
            $identifier = $body['identifier'];
            $status = $body['status'];

            if (!$moduleManager->is_installed($identifier)) {
                return JSONResponseFactory::error('Add-on is not installed.');
            }
            $addon = new ManageTenant($database, \isys_application::instance()->app_path . 'src/classes/modules/');
            $addon->setIdentifier($identifier);

            $result = false;
            if (!$status) {
                $result = $addon->deactivate();
            } else {
                $result = $addon->activate();
            }

            if ($result !== true) {
                return JSONResponseFactory::error('Unable to perform action.');
            }

            return JSONResponseFactory::success();
        } catch (\Throwable $e) {
            return JSONResponseFactory::error($e->getMessage());
        }
    }
}
