<?php
class Language extends AppModel {

	var $name = 'Language';

	var $order = array('Language.ordering' => ASC);

	var $displayField = 'title';

	var $displayImage = 'Icon';

	var $hasOne = array(
		'Icon' => 'Upload jpeg jpg png gif',
	);

	var $validate = array(
		'title' => 'notBlank',
		'locale' => 'notBlank'
	);

	function getLanguages() {
		return $this->find('all', array(
			'Get all active languages',
			'pack' => 'locale',
			'conditions' => array(
				'Language.is_active' => true)
		));
	}

	function beforeSave($options = array()) {

		# Trying to deactivate default language
		if(isset($this->data[$this->alias]['is_active']) && empty($this->data[$this->alias]['is_active']) && $this->hasAny(array('id' => $this->id, 'is_default' => true))) {
			$this->data[$this->alias]['is_active'] = true;
			$this->invalidate('is_active', __('Default language cannot be deactivated.'));
			if(isset($this->data[$this->alias]['is_default'])) {
				return false;
			}
		}
		# Trying to deactivate current language
		if(isset($this->data[$this->alias]['is_active']) && $this->data[$this->alias]['is_active'] == Configure::read('Config.language')) {
			$this->invalidate('is_active', __('You cannot deactivate language that you are using.'));
			if(isset($this->data[$this->alias]['is_default'])) {
				return false;
			}
		}
		# Trying to set inactive language as default
		if(!empty($this->data[$this->alias]['is_default']) && ((isset($this->data[$this->alias]['is_active']) && empty($this->data[$this->alias]['is_active'])) || (!isset($this->data[$this->alias]['is_active']) && $this->hasAny(array('id' => $this->id, 'is_active' => false))))) {
			$this->invalidate('is_default', __('Inactive language cannot be set as a default one'));
			return false;
		}

		return true;
	}

	function refreshTables() {
		die('Prevented, contact administrator');
		$this->BEGIN();

		$languages = $this->find('list', array('fields' => array('locale')));

		# Get column data #
		$cm = ConnectionManager::getDataSource('default');
		$query = "
			SELECT `table_name`, `column_name`, `column_default`, `column_type`, `is_nullable`
			FROM `information_schema`.`columns` AS `Column`
			WHERE `column_name` LIKE '%\_\_%' AND `table_schema` = '{$cm->config['database']}'
			ORDER BY `table_name` ASC, `ordinal_position` ASC";
		$schema = $this->query($query);
		# Regroup the columns #
		$tables = array();
		foreach($schema as $column) {
			$table = array_shift($column['Column']);
			list($field, $locale) = split('__', array_shift($column['Column']));
			if(!isset($tables[$table][$field])) {
				$tables[$table][$field] = array_merge(reset($column), array('locale' => array($locale)));
			} else {
				$tables[$table][$field]['locale'] = array_merge($tables[$table][$field]['locale'], array($locale));
			}
		}

		# Find unmaching columns #
		$queries = array();
		foreach($tables as $table => $columns) {
			foreach($columns as $name => $column) {
				if($diff = array_reverse(array_diff($languages, $column['locale']))) {
					$after = end($column['locale']);
					$null = !$column['is_nullable'] ? ' NOT NULL' : '';
					$default = $column['column_default'] !== null ? " DEFAULT '{$column['column_default']}'" : '';
					foreach($diff as $locale) {
						$queries[] = "ALTER TABLE `{$table}` ADD `{$name}__{$locale}` {$column['column_type']}{$null}{$default} AFTER `{$name}__{$after}`";
					}
				}
				if($diff = array_diff($column['locale'], $languages)) {
					foreach($diff as $locale) {
						$queries[] = "ALTER TABLE `{$table}` DROP `{$name}__{$locale}`";
					}
				}
			}
		}

		# Execute queries #
		foreach($queries as $query) {
			$this->query($query);
		}
		$this->COMMIT();
	}

	function beforeDelete($cascade = true) {
		//$this->requestAction('/tools/dump/archive', array('return'));
		Cache::delete('languages');
		Cache::delete('dictionary');
		return true;
	}

	function afterSave($created, $options = array()) {
		Cache::delete('languages');
		Cache::delete('dictionary');
	}


# ~ Append locale to url - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function urlLocale($link) {
		if(!CMS && Configure::read('Feature.hide_default_language_prefix')) {
			if(Configure::read('Config.language') == Configure::read('Config.default_language')) {
				return $link;
			}
		}
		return '/' . Configure::read('Config.language') . $link;
	}

# ~ Remove locale from url - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function removeUrlLocale($link) {
		if(!CMS && Configure::read('Feature.hide_default_language_prefix')) {
			if(Configure::read('Config.language') == Configure::read('Config.default_language')) {
				return $link;
			}
		}
		$locale = Configure::read('Config.language');
		$link = preg_replace('/^\/' . $locale . '/', '', $link);
		return $link;
	}

}

