<?php

use idoit\AddOn\ActivatableInterface;
use idoit\AddOn\AuthableInterface;
use idoit\AddOn\ExtensionProviderInterface;
use idoit\AddOn\InstallableInterface;
use idoit\AddOn\LicensableInterface;
use idoit\AddOn\RoutingAwareInterface;
use idoit\Exception\JsonException;
use idoit\Module\SyneticsFlows\Auth;
use idoit\Module\SyneticsFlows\FlowsExtension;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\PhpFileLoader;

/**
 * i-doit
 *
 * Add-on synetics_flows module class.
 *
 * @package   synetics_flows
 * @copyright synetics
 * @license   https://www.i-doit.com/
 */
class isys_module_synetics_flows extends isys_module implements InstallableInterface, ActivatableInterface, ExtensionProviderInterface, AuthableInterface, LicensableInterface, RoutingAwareInterface
{
    // Define, if this module shall be displayed in the named menus.
    const DISPLAY_IN_MAIN_MENU = true;
    const DISPLAY_IN_SYSTEM_MENU = false;
    const MAIN_MENU_REWRITE_LINK = false;
    const SETTING_KEY = 'flow.installed';

    /**
     * @var bool
     */
    protected static $m_licenced = false;

    /**
     * @return void
     * @throws \Exception
     */
    public function start()
    {
        $indexUrl = isys_application::instance()->container->get('route_generator')->generate('synetics_flows.index');

        header('Location: ' . $indexUrl);
        die;
    }

    /**
     * @return Auth
     */
    public static function getAuth()
    {
        return Auth::instance();
    }

    /**
     * Initializes the module.
     *
     * @param isys_module_request $p_req
     */
    public function init(isys_module_request $p_req)
    {
        $container = isys_application::instance()->container;
        if ($container->has('idoit.flows.signal')) {
            // connect to signals
            $container->get('idoit.flows.signal');
        }
    }

    /**
     * Checks if a add-on is installed.
     *
     * @return int|bool
     */
    public static function isInstalled()
    {
        return isys_module_manager::instance()
            ->is_installed('synetics_flows');
    }

    /**
     * Basic installation process for all mandators.
     *
     * @param isys_component_database $tenantDatabase
     * @param isys_component_database $systemDatabase
     * @param int $moduleId
     * @param string $type
     * @param int $tenantId
     *
     * @return bool
     * @throws JsonException
     * @throws isys_exception_dao
     * @throws isys_exception_database
     */
    public static function install($tenantDatabase, $systemDatabase, $moduleId, $type, $tenantId)
    {
        $systemSettings = isys_application::instance()->container->get('settingsSystem');
        if (!$systemSettings->get(self::SETTING_KEY, null)) {
            isys_application::instance()->container->get('settingsSystem')->set(self::SETTING_KEY, time());
        }

        return true;
    }

    /**
     * Uninstall add-on for all mandators.
     *
     * @param isys_component_database $tenantDatabase
     *
     * @return boolean
     * @throws JsonException
     * @throws isys_exception_dao
     */
    public static function uninstall($tenantDatabase)
    {
        return true;
    }

    /**
     * Checks if a add-on is active.
     *
     * @return integer|bool
     */
    public static function isActive()
    {
        return isys_module_manager::instance()
            ->is_installed('synetics_flows', true);
    }

    /**
     * Method that is called after clicking "activate" in admin center for specific mandator.
     *
     * @param isys_component_database $tenantDatabase
     *
     * @return boolean
     * @throws JsonException
     * @throws isys_exception_dao
     */
    public static function activate($tenantDatabase)
    {
        return true;
    }

    /**
     * Method that is called after clicking "deactivate" in admin center for specific mandator.
     *
     * @param isys_component_database $tenantDatabase
     *
     * @return boolean
     * @throws isys_exception_dao
     * @throws JsonException
     */
    public static function deactivate($tenantDatabase)
    {
        return true;
    }

    /**
     * @return FlowsExtension
     */
    public function getContainerExtension()
    {
        return new FlowsExtension();
    }

    /**
     * @return bool
     * @throws Exception
     */
    public static function isLicensed()
    {
        return self::$m_licenced || self::hasTrial();
    }

    /**
     * Check if user has trial
     *
     * @return bool
     * @throws Exception
     */
    public static function hasTrial(): bool
    {
        $trialUsageInDays = self::getTrialUsageInDays();

        if ($trialUsageInDays !== null) {
            return $trialUsageInDays < 30;
        }

        return false;
    }

    /**
     * @return int|null
     * @throws Exception
     */
    public static function getTrialUsageInDays(): ?int
    {
        $installationDate = isys_application::instance()->container->get('settingsSystem')->get(self::SETTING_KEY, null);

        if ($installationDate) {
            $start = new DateTime();
            $start->setTimestamp((int)$installationDate);

            return $start->diff(new DateTime())->days;
        }

        return null;
    }

    /**
     * Check if user is in trial phase
     *
     * @return bool
     * @throws Exception
     */
    public static function isTrial(): bool
    {
        return !self::$m_licenced && self::hasTrial();
    }

    /**
     * @param $isLicensed
     *
     * @return void
     */
    public static function setLicensed($isLicensed)
    {
        static::$m_licenced = $isLicensed;
    }

    /**
     * @return void
     * @throws Exception
     */
    public static function registerRouting(): void
    {
        isys_application::instance()->container->get('routes')
            ->addCollection((new PhpFileLoader(new FileLocator(__DIR__)))->load('config/routes.php'));
    }
}
