<?php namespace ProcessWire;

/**
 * ProcessWire E-Mail Fieldtype
 *
 * Fieldtype for holding an email address. 
 *
 * For documentation about the fields used in this class, please see:  
 * /wire/core/Fieldtype.php
 * 
 * ProcessWire 3.x, Copyright 2023 by Ryan Cramer
 * https://processwire.com
 *
 *
 */
class FieldtypeEmail extends FieldtypeText {

	public static function getModuleInfo() {
		return array(
			'title' => 'E-Mail',
			'version' => 101,
			'summary' => 'Field that stores an e-mail address',
		);
	}

	/**
	 * Get max email address length
	 * 
	 * @return int
	 * 
	 */
	public function getMaxEmailLength() {
		return $this->wire()->database->getMaxIndexLength();
	}

	/**
	 * Get Inputfield module for this Fieldtype
	 * 
	 * @param Page $page
	 * @param Field $field
	 * @return InputfieldEmail
	 * 
	 */
	public function getInputfield(Page $page, Field $field) {
		/** @var InputfieldEmail $inputfield */
		$inputfield = $this->wire()->modules->get('InputfieldEmail'); 
		$inputfield->addClass($this->className());
		return $inputfield; 
	}

	/**
	 * Sanitize value for page
	 * 
	 * @param Page $page
	 * @param Field $field
	 * @param string $value
	 * @return string
	 * 
	 */
	public function sanitizeValue(Page $page, Field $field, $value) {
		$sanitizer = $this->wire()->sanitizer;
		$max = $this->getMaxEmailLength();
		if(strlen($value) > $max && $sanitizer->getTextTools()->strlen($value) > $max) return '';
		return $sanitizer->email($value, array(
			'allowIDN' => (int) $field->get('allowIDN')
		));
	}

	/**
	 * Get database schema for field
	 * 
	 * @param Field $field
	 * @return array
	 * 
	 */
	public function getDatabaseSchema(Field $field) {
		$len = $this->getMaxEmailLength();
		$schema = parent::getDatabaseSchema($field); 
		$schema['data'] = "varchar($len) NOT NULL default ''";
		
		if($field->hasFlag(Field::flagUnique) != (bool) $field->flagUnique) {
			if($this->wire()->getStatus() >= ProcessWire::statusReady) {
				$fields = $this->wire()->fields;
				$fields->tableTools()->checkUniqueIndex($field);
			}
		}
		
		return $schema;
	}

	/**
	 * Is given value one that doesn’t need to be stored in DB?
	 * 
	 * @param Page $page
	 * @param Field $field
	 * @param mixed $value
	 * @return bool
	 * 
	 */
	public function isDeleteValue(Page $page, Field $field, $value) {
		return empty($value);
	}

	/**
	 * Advanced configuration for field
	 * 
	 * @param Field $field
	 * @return InputfieldWrapper
	 * 
	 */
	public function ___getConfigAdvancedInputfields(Field $field) {
		$inputfields = parent::___getConfigAdvancedInputfields($field);
		$fields = $this->wire()->fields;
		$f = $fields->tableTools()->getUniqueIndexInputfield($field); 
		$inputfields->prepend($f);
		return $inputfields;
	}
	
}


