<?php

/**
 * Description of ImporterController
 *
 * @author NE
 */

class Backend_ImporterController extends RCMS_Core_BaseController {

	private $_errors = array();

	public function init() {
		$this->_model = new Default_Model_ImporterModel();
		parent::init();
		parent::checkLogin();
		$this->_cache->clean('all');
    }

	public function indexAction() {
		$this->_helper->layout->disableLayout();
		$form = new RCMS_Form_ImporterForm();
		$form->getElement('websiteUrl')->setValue($this->getWebSiteUrl());
		$form->setDecorators(array(
			array('ViewScript', array('viewScript' => 'forms/importer.phtml'))
		));
		$this->view->form = $form;
		if(($this->_errors = $this->_session->errors) != '') {
			$this->view->errors = $this->_errors;
			unset($this->_session->errors);
		}
		if(isset($this->_session->imported) && $this->_session->imported == 'success') {
			$this->view->success = true;
			unset($this->_session->imported);
		}
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
	}

	public function runimportAction() {
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender(true);

		if($this->getRequest()->isPost()) {
			$websiteUrl = htmlentities(trim($this->getRequest()->getParam('siteUrl')));
			if(empty ($websiteUrl)) {
				$this->_errors[] = 'Website url should not be empty.';
			}
			elseif(!preg_match('~https?:((//)|(\\\\))+[\w\d:#@%/;$()\~_?\+-=\\\.&]+~', $websiteUrl)) {
				$this->_errors[] = 'Invalid website url.';
			}

			if(empty($this->_errors)) {
				$importer = new RCMS_Object_Grubber_Grubber($websiteUrl);
				$grubbedData = $importer->grub();
				if(!empty ($grubbedData) && is_array($grubbedData)) {
					$updater = new RCMS_Object_Updater_Updater();
					$updater->saveGrubbedPages($grubbedData);
					$this->_session->imported = 'success';
				}
				else {
					$this->_errors[] = 'No data to import.';
				}
			}
		}
		$this->_session->errors = $this->_errors;
		$this->_forward('index');
	}

}
