<?php


class SupsysticTablesPro_Migration_Model_Importer extends SupsysticTables_Core_BaseModel
{
	public function import(array $file)
	{
		if ($file['error'] !== UPLOAD_ERR_OK) {
			switch ($file['error']) {
				case UPLOAD_ERR_INI_SIZE:
				case UPLOAD_ERR_FORM_SIZE:
					$message = $this->environment->translate('The uploaded file exceeds the max size of uploaded files.');
					break;
				case UPLOAD_ERR_PARTIAL:
					$message = $this->environment->translate('The uploaded file was only partially uploaded.');
					break;
				case UPLOAD_ERR_NO_FILE:
					$message = $this->environment->translate('No file was uploaded.');
					break;
				case UPLOAD_ERR_NO_TMP_DIR:
					$message = $this->environment->translate('Missing a temporary folder.');
					break;
				case UPLOAD_ERR_CANT_WRITE:
					$message = $this->environment->translate('Failed to write file to disk.');
					break;
				default:
					$message = $this->environment->translate('Unexpected error.');
			}
			throw new SupsysticTablesPro_Migration_Exception_Upload($message);
		}

		$this->importFromFile($file['tmp_name']);
	}

	private function importFromFile($file)
	{
		if (!is_readable($file)) {
			throw new RuntimeException(
				sprintf('File "%s" is not readable.', $file)
			);
		}

		if (false === $data = file_get_contents($file)) {
			throw new RuntimeException(
				sprintf('Failed to read file "%s".', $file)
			);
		}
		$delim = '----------------------------------';
		$prefix = '%prefix%';
		if(!strpos($data, $delim) || !strpos($data, $prefix)) {
			throw new SupsysticTablesPro_Migration_Exception_Upload($this->environment->translate('Invalid file format.'));
		}
		$preTable = $this->getPrefix();

		$data = str_replace('%prefix%', $preTable, $data);
		$queries = explode($delim, $data);
		$queries = array_map('trim', $queries);
		$queries = array_filter($queries);
		$first = true;

		foreach($queries as $q) {
			if($first) {
				if(strpos($q, ',`settings`,`woo_settings`')) {
					$existsWoo = $this->db->get_results("Show columns from `".$preTable."tables` like 'woo_settings'");
					if($this->db->last_error) {
						throw new RuntimeException($this->db->last_error);
					}
					if(!isset($existsWoo) || !is_array($existsWoo) || sizeof($existsWoo) == 0) {
						$this->db->query("ALTER TABLE `".$preTable."tables` ADD COLUMN `woo_settings` TEXT NULL AFTER `settings`");
						if($this->db->last_error) {
							throw new RuntimeException($this->db->last_error);
						}
					}
				}
				$first = false;
			}

			$this->db->query($q);
			if($this->db->last_error) {
				throw new RuntimeException($this->db->last_error);
			}
		}
	}
}
