<?php namespace ProcessWire;

require_once(dirname(__FILE__) . '/FieldtypeLanguageInterface.php'); 

/**
 * Multi-language capable text field
 *
 * ProcessWire 3.x (development), Copyright 2015 by Ryan Cramer
 * https://processwire.com
 *
 *
 */

class FieldtypeTextLanguage extends FieldtypeText implements FieldtypeLanguageInterface {

	public static function getModuleInfo() {
		return array(
			'title' => 'Text (Multi-language)',
			'version' => 100,
			'summary' => 'Field that stores a single line of text in multiple languages',
			'permanent' => false,
			'requires' => array('LanguageSupportFields'),
			);
	}

	/**
	 * Sanitize value for storage
	 *
	 */
	public function sanitizeValue(Page $page, Field $field, $value) {
		if(is_object($value) && $value instanceof LanguagesPageFieldValue) {
			// great, already what we wanted
		} else {
			// convert it to a LanguagesPageFieldValue
			$str = (string) $value; 
			$value = $page->getUnformatted($field->name); 
			if(is_string($value)) $value = new LanguagesPageFieldValue($page, $field, $value); // #98
			$value->setLanguageValue($this->wire('user')->language->id, $str); 
		}
		return $value; 
	}

	/**
	 * Return the database schema in specified format
	 *
	 */
	public function getDatabaseSchema(Field $field) {
	
		$schema = parent::getDatabaseSchema($field);
		$languageSupport = $this->wire('modules')->get('LanguageSupport'); 
	
		// note that we use otherLanguagePageIDs rather than wire('languages') because
		// it's possible that this method may be called before the languages are known 
		foreach($languageSupport->otherLanguagePageIDs as $languageID) {
			// $schema['data' . $languageID] = $schema['data'];
			$schema['data' . $languageID] = 'text';
			$schema['keys']["data_exact{$languageID}"] = "KEY `data_exact{$languageID}` (`data{$languageID}`(250))";
			$schema['keys']["data{$languageID}"] = "FULLTEXT KEY `data{$languageID}` (`data{$languageID}`)";
		}
	
		return $schema;
	}

	/**
	 * Format value for output, basically typcasting to a string and sending to textformatters from FieldtypeText
	 *
	 */
	public function formatValue(Page $page, Field $field, $value) {
		return parent::formatValue($page, $field, (string) $value); 
	}

}

