<?php


class SupsysticTablesPro_Migration_Controller extends SupsysticTables_Core_BaseController
{
	/**
     * Generates download url.
     * @param \Rsc_Http_Request $request
     * @return \Rsc_Http_Response
     */
    public function generateUrlAction(Rsc_Http_Request $request)
    {
		$id = $request->post->get_esc_html('id');

		$slug = $this->getEnvironment()->getMenu()->getMenuSlug();

        return $this->ajaxSuccess(array(
            'url' => admin_url(
                sprintf(
                    'admin.php?page=%s&module=migration&migration-supsystic-table=true&id=%s',
                    $slug,
					$id
                )
            )
        ));
    }

    public function export(Rsc_Http_Request $request)
    {
		$id = $request->query->get_esc_html('id');
		$ids = explode(';', $id);
		if(!is_array($ids)) {
			wp_die(sprintf($this->translate('The table IDs %s not found.'), $id));
		}
		$tables = $this->getModel('tables');
		$exporter = $this->getModel('exporter', $this->getModule());

		foreach($ids as $i => $id) {
			$table = $tables->getById((int)$id);
			if (null === $table) {
				wp_die(sprintf($this->translate('The table ID %s not found.'), $id));
			}
		}
		$exporter->export($ids);
        die;

    }

	public function importAction(Rsc_Http_Request $request)
    {
		$file = $request->files->get('file');
		$importer = $this->getModel('importer', $this->getModule());
		try {
			$importer->import($file);
		} catch (SupsysticTablesPro_Migration_Exception_Upload $e) {
			return $this->response('@migration/upload_error.twig', array('error' => $e));
		}

		return $this->redirect($this->generateUrl('tables', 'index'));
    }

    /**
     * @return SupsysticTablesPro_Migration_Module
     */
    protected function getModule()
    {
        $resolver = $this->getEnvironment()->getResolver();

        return $resolver->getModulesList()->get('migration');
    }
}
