<?php

/**
 * Class SupsysticTablesPro_Migration_Module
 */
class SupsysticTablesPro_Migration_Module extends SupsysticTables_Core_BaseModule
{
    /**
     * {@inheritdoc}
     */
    public function onInit()
    {
        $this->setOverloadController(true);
        $this->addImportDialog();
        $this->onAfterUiLoaded();
        $this->handleMigrationRequest();
    }

	private function addImportDialog()
	{
		$dispatcher = $this->getEnvironment()->getDispatcher();
		$dispatcher->on('tables-index-footer', array($this, 'renderDialog'));
	}

    public function renderDialog()
    {
        $twig = $this->getEnvironment()->getTwig();
        $twig->display('@migration/partials/migration-dialog.twig');
    }

	private function handleMigrationRequest()
	{
		if (!$this->getRequest()->query->has('migration-supsystic-table')) {
			return;
		}
		$config = $this->getEnvironment()->getConfig();
		$path = $config->get('pro_modules_path');

		$this->getController()->export($this->getRequest());
	}

    private function onAfterUiLoaded()
    {
		$environment = $this->getEnvironment();
        $version = $this->getConfig()->get('plugin_version_pro');
        //$location = untrailingslashit(plugin_dir_url(__FILE__));
		$hookName = is_admin() ? 'admin_enqueue_scripts' : 'wp_enqueue_scripts';

		$ui = $this->getEnvironment()->getModule('ui');

		if ($environment->isModule('tables') && $environment->isAction('index')) {
			$ui->add(
				$ui->createScript('supsystic-tables-view-migration-js')
					->setHookName('admin_enqueue_scripts')
					->setModuleSource($this, 'js/tables.migration.js')
					->setVersion($version)
			);
		}
    }
}
