<?php

namespace ggbn;

use Yii;
use yii\base\Widget;
use yii\helpers\Url;
use yii\helpers\Html;
use yii\web\JsExpression;
use kartik\widgets\Typeahead;
use yii\bootstrap\Dropdown;
use kartik\field\FieldRange;
use kartik\widgets\ActiveForm;
use kartik\checkbox\CheckboxX;

/*
 * this CreateFormManager handles all functions required to create fields etc.
 * <br/><br/>
 * @author Gabriele Droege, Sybille Buers, Patricia Kelbert (BGBM, GGBN/DNA Bank Network) <contact@dnabank-network.org>
 * @version 1.0
 * @package Package
 * @var $model SearchForm
 * @var $selectionLists - created in the controller
 * @var $form CActiveForm
 * @var $htmlOpts Design facts
 * @copyright Copyright © 2011 DNA Bank Network http://www.dnabank-network.org
 * <br/>The contents of this file are subject to the Mozilla Public License Version 1.1
 * @filesource
 * @license http://www.mozilla.org/MPL/ MPL
 */
class CreateFormManager {
	
	// // create parameters for autosuggest widgets:
	public static function autosuggestOptions($model, $listTitle, $htmlOptions) {
		if (isset ( $htmlOptions )) {
			if (isset ( $htmlOptions ['value'] ))
				$model->$htmlOptions ['name'] = $htmlOptions ['value'];
		}
		$url = Yii::$app->getUrlManager ()->createUrl ( 'serverscripts/suggestion-list' );
		if (! Yii::$app->params ['noBack']) {
		try {
			$template = '<label  name="' . $listTitle . '" class="repo-language" value="{{value}}"><span class="left">{{label}}</span><br/><span class="left light">{{hierarchy0}}<b>{{hierarchy1}}</b>{{hierarchy2}}</span><br/><span class="left why">{{reason0}}<b>{{reason1}}</b>{{reason2}}</span></label>';
				
		} catch ( Exception $e ) {
			try {
				$template = '<label  name="' . $listTitle . '" class="repo-language" value="{{value}}"><span class="left">{{label}}</span><br/><span class="left light">{{hierarchy0}}<b>{{hierarchy1}}</b>{{hierarchy2}}</span></label>';
			} catch ( Exception $e ) {
				$template = '<label  name="' . $listTitle . '" class="repo-language" value="{{value}}"><span class="left">{{label}}</span></label>';
			}
		}
		}
		else{
			try {
				$template = '<label  name="' . $listTitle . '" class="repo-language" value="{{value}}"><span class="left">{{label}}</span><br/><span class="left light">{{hierarchy0}}<b>{{hierarchy1}}</b>{{hierarchy2}}</span><span class="left why">&nbsp;/&nbsp; {{reason0}} <b>{{reason1}}</b> {{reason2}}</span></label>';
			
			} catch ( Exception $e ) {
				try {
					$template = '<label  name="' . $listTitle . '" class="repo-language" value="{{value}}"><span class="left">{{label}}</span><br/><span class="left light">{{hierarchy0}}<b>{{hierarchy1}}</b>{{hierarchy2}}</span></label>';
				} catch ( Exception $e ) {
					$template = '<label  name="' . $listTitle . '" class="repo-language" value="{{value}}"><span class="left">{{label}}</span></label>';
				}
			}
		}
		
// 		Yii::info("form template: ".$template);
		
		$formValues = [ ];
		
		return [ 
				'options' => [ 
						'placeholder' => 'Filter as you type ...' 
				],
				'pluginOptions' => [ 
						'highlight' => FALSE 
				],
				'dataset' => [ 
						[ 
								'remote' =>['url'=> $url . '?listTitle=' . $listTitle . '&term=%QUERY',
										'wildcard' => '%QUERY',],
								'display' => 'value',
								'limit' => 10,
								'templates' => [ 
										'empty' => '<div class="text-error">Unable to find records for selected query.</div>',
										'suggestion' => new JsExpression ( "Handlebars.compile('{$template}')" ) 
								] 
						] 
				] 
		];
	}
	public static function createField($controller, $model, $form, $key, $param, $selectionLists, $htmlOpts, $selectedValue) {
		$currentType = "test";
		foreach ( $param as $paramKey => $paramV )
			if (strcmp ( $paramKey, "type" ) == 0)
				$currentType = $paramV;
			
			// Yii::info ( "currenttype : " . $currentType );
		switch ($currentType) {
			
			case 'select' :
				// get the values either from the definition in the form model
				// or from the index
				if (isset ( $param ['valueList'] )) {
					$attributeList = $param ['valueList'];
				} else // get selection list from index
				{
					// actually the the field should never be not set!
					$attributeList = isset ( $selectionLists ) ? $selectionLists [$key] : array ();
				}
				
				$selectField = [ ];
				foreach ( $attributeList as $kk => $vv ) {
					if ($key === "sampletype" && $vv != "---") {
						if (preg_match ( "/ \(\d* \/ \d*\)/", $vv ))
							$selectField [preg_replace ( "/ \(\d* \/ \d*\)/", "", $vv )] = "records with " . $vv;
						else
							$selectField [preg_replace ( "/ \(\d*\)/", "", $vv )] = "records with " . $vv;
					} else {
						if (preg_match ( "/ \(\d* \/ \d*\)/", $vv ))
							$selectField [preg_replace ( "/ \(\d* \/ \d*\)/", "", $vv )] = $vv;
						else
							$selectField [preg_replace ( "/ \(\d*\)/", "", $vv )] = $vv;
					}
				}
				
				// as the select tag we use here, uses the size attribute not for the length of the
				// field, we move the value to a style attribute
				if (isset ( $htmlOpts ['size'] )) {
					$size = $htmlOpts ['size'];
					unset ( $htmlOpts ['size'] );
				} else {
					$size = $model->getFieldSize () * 8;
				}
				
				// Rukeia 16-03-2015: $onlyFieldName contains the $selectionLists values without record counts in brackets behind, e.g., "Algeria" instead of "Algeria (49)"
				$onlyFieldName = array ();
				foreach ( $selectionLists [$key] as $value ) {
					if (preg_match ( "/ \(\d* \/ \d*\)/", $value ))
						$value = preg_replace ( "/ \(\d* \/ \d*\)/", "", $value );
					else
						$value = preg_replace ( "/ \(\d*\)/", "", $value );
					array_push ( $onlyFieldName, $value );
				}
				
				// Rukeia 16-03-2015: $listPos is the position of the selected value in $selectionLists
				$listPos = array_search ( $selectedValue, $onlyFieldName );
				
				$model->$key = $selectedValue;
// 				if((strpos($key,"indexHerbarorium"))!==false)
// 				echo $form->field ( $model, $key )->dropdownList ( $selectField, [
// 						'$key','disabled'=>true   
// 				] );
// 				else
				echo $form->field ( $model, $key )->dropdownList ( $selectField, [ 
						'$key' 
				] );
				
				break;
			case 'suggest' :
				$options = CreateFormManager::autosuggestOptions ( $model, $key, $htmlOpts );
				echo $form->field ( $model, $key )->widget ( Typeahead::classname (), $options );
				break;
			
			case 'number' :
				echo $form->numberField ( $model, $key, $htmlOpts );
				break;
			// TODO do we need range bars?
			case 'range' :
// 				foreach ( $htmlOpts as $ht => $hv )
// 					Yii::info ( $ht . " ==> " . $hv );
				echo FieldRange::widget ( [
						// 'form' => $form,
						// 'model' => $model,
						'label' => $key,
						// 'attribute1' => $htmlOpts["attribute1"],
						// 'attribute2' => $htmlOpts["attribute2"],
						'name1' => $htmlOpts ["attribute1"],
						'options1' => [ 
								"placeholder" => $htmlOpts ["attribute1value"] 
						],
						'name2' => $htmlOpts ["attribute2"],
						'type' => $htmlOpts ["type"],
						'label' => $htmlOpts ["name"],
						'options2' => [ 
								"placeholder" => $htmlOpts ["attribute2value"] 
						] 
				] );
				if (isset ( $htmlOpts ["attribute3"] )) {
					echo FieldRange::widget ( [
							// 'form' => $form,
							// 'model' => $model,
							// 'attribute1' => $htmlOpts["attribute1"],
							// 'attribute2' => $htmlOpts["attribute2"],
							'name1' => $htmlOpts ["attribute3"],
							'options1' => [ 
									"placeholder" => $htmlOpts ["attribute3value"] 
							],
							'name2' => $htmlOpts ["attribute4"],
							'options2' => [ 
									"placeholder" => $htmlOpts ["attribute4value"] 
							],
							'type' => $htmlOpts ["type"] 
					] );
				}
				
				break;
			case 'checkbox' :
				$model->$key=$selectedValue;
				echo $form->field($model, $key)->widget(CheckboxX::classname(), [
						'autoLabel'=>true, 'name'=>$htmlOpts ["name"],'pluginOptions'=>['threeState'=>false],
						'class'=>'control-label'
				])->label(false);
			//	echo $form->checkBox ( $model, $key, $htmlOpts );
				break;
			case 'radio' :
				if($key==='cites')
				echo $form->field ( $model, $key )->radioList ( [ 
						'exclude' => 'Exclude listed species',
						'include' => 'Include listed species',
						'citesOnly' => 'Only listed species' 
				] );
				
				if($key==='sampleavailability')
				echo $form->field ( $model, $key )->radioList ( [
						'only' => 'only available samples',
						'all' => 'all samples'
				] );
 				echo "<br/><div class='clearer'></div>";
				break;
			case 'text' :
				echo $form->field ( $model, $key )->textInput ( $htmlOpts );
				break;
			
			case 'hidden' :
				echo $form->field ( $model, $key )->hiddenInput ()->label ( '' );
				break;
			default :
				
				// echo $form->textField ( $model, $key, $htmlOpts );
				echo $form->field ( $model, $key )->textInput ( $htmlOpts );
				break;
		}
		//End switch
}
}
?>