<?php

/**
 * Class SupsysticTablesPro_Importer_Module
 */
class SupsysticTablesPro_Importer_Module extends SupsysticTables_Core_BaseModule
{
    private $frontendImportErrorMsg = '';

	public function onInit()
    {
        parent::onInit();

		$this->addImportDialog();
        $this->onAfterUiLoaded();
		$this->addImportFeature();
		$this->registerImportBtnShortcode();
    }

	private function addImportFeature()
	{
		$dispatcher = $this->getEnvironment()->getDispatcher();
		$dispatcher->on('tables-view-features', array($this, 'renderImportFeatures'));
	}

	public function renderImportFeatures($table)
	{
		$twig = $this->getEnvironment()->getTwig();
		$twig->display('@importer/features/import.twig', array('table' => $table));
	}

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

    public function renderDialog()
    {
        $twig = $this->getEnvironment()->getTwig();
        $twig->display('@importer/partials/import-dialog.twig', array(
            'table_id' => $this->getRequest()->query->get_esc_html('id'),
			'is_frontend' => false,
        ));
    }

    private function onAfterUiLoaded()
    {
		/** @var SupsysticTables_Ui_Module $ui */
		$ui = $this->getEnvironment()->getModule('ui');
		
		if($this->getEnvironment()->isModule('tables', 'view')) {
			$ui->add(
				$ui->createScript('supsystic-tables-view-importer-js')
					->setHookName('admin_enqueue_scripts')
					->setModuleSource($this, 'js/tables.view.importer.js')
					->setVersion('1.0')
			);
        }
    }

	public function autoUpdateTableFromGoogle($id, $table) {
		$this->getController()->includePHPExcel();
		$importer = $this->getController()->getImporter();
		$settings = array(
			'url' => $table->settings['features']['import']['google']['link']
		);

		try {
			$importer->importSpreadheets($id, $settings);
		} catch (SupsysticTablesPro_Importer_Exception $e) {
			$environment = $this->getEnvironment();
			throw new Exception(sprintf($environment->translate('Failed to import selected file: %s'), $e->getMessage()));
		} catch (SupsysticTablesPro_Importer_Exception_UnsupportedType $e) {
			$environment = $this->getEnvironment();
			throw new Exception($environment->translate('Failed to import data from the uploaded file'));
		}
	}

	private function registerImportBtnShortcode()
	{
		$config = $this->getEnvironment()->getConfig();
		$config->add('import_form_shortcode_name', 'supsystic-tables-import-form');
		add_shortcode($config->get('import_form_shortcode_name'), array($this, 'doImportBtnShortcode'));

		$dispatcher = $this->getEnvironment()->getDispatcher();
		$dispatcher->on('table-shortcodes-list', array($this, 'addImportBtnShortcodeInfo'));
	}

	public function addImportBtnShortcodeInfo($shortcodes) {
		$environment = $this->getEnvironment();
		$config = $environment->getConfig();
		$shortcodes['import_form_shortcode'] = array(
			'name' => $config->get('import_form_shortcode_name'),
			'label' => $environment->translate('Frontend Import Form'),
			'attrs' => '',
		);
		return $shortcodes;
	}

	public function doImportBtnShortcode($attributes)
	{
		$environment = $this->getEnvironment();

		if(empty($attributes['id'])) {
			return sprintf($environment->translate('The table with ID %d not exists.'), $attributes['id']);
		}
		$config = $this->getEnvironment()->getConfig();
		$twig = $environment->getTwig();
		$core = $environment->getModule('core');

		if($core->getMainRequestError()) {
			return $core->getMainRequestError();
		}
		return $twig->render('@importer/partials/import-dialog-frontend.twig', array(
			'table_id' => $attributes['id'],
			'is_frontend' => true,
			'form_action' => $config['plugin_menu']['menu_slug'],
			'form_error_msg' => $this->getFrontendImportErrorMsg(),
		));
	}

	public function setFrontendImportErrorMsg($message) {
		$this->frontendImportErrorMsg = $message;
	}
	public function getFrontendImportErrorMsg() {
		return $this->frontendImportErrorMsg;
	}
}