import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FormArray, FormControl, FormGroup, FormGroupDirective, NgForm,} from '@angular/forms';
import {DatasetProfileFieldViewStyle} from '@app/core/common/enum/dataset-profile-field-view-style';
import {ValidationType} from '@app/core/common/enum/validation-type';
import {DatasetProfileService} from '@app/core/services/dataset-profile/dataset-profile.service';
import {EnumUtils} from '@app/core/services/utilities/enum-utils.service';
import {RuleEditorModel} from '@app/ui/admin/dataset-profile/admin/rule-editor-model';
import {BaseComponent} from '@common/base/base.component';
import {Subscription} from 'rxjs';
import {ViewStyleType} from './view-style-enum';
import {DatasetProfileComboBoxType} from '@app/core/common/enum/dataset-profile-combo-box-type';
import {ErrorStateMatcher} from '@angular/material/core';
import {MatDialog} from '@angular/material/dialog';
import {MatSlideToggleChange} from '@angular/material/slide-toggle';
import {DefaultValue, Field} from '@app/core/model/admin/dataset-profile/dataset-profile';
import {DatasetProfileInternalDmpEntitiesType} from '@app/core/common/enum/dataset-profile-internal-dmp-entities-type';
import {FieldEditorModel} from '../../../admin/field-editor-model';
import {
	AutoCompleteFieldData,
	BooleanDecisionFieldData,
	CheckBoxFieldData,
	CurrencyFieldData,
	DataRepositoriesFieldData,
	DatasetIdentifierFieldData,
	DatePickerFieldData,
	DmpsAutoCompleteFieldData,
	ExternalDatasetsFieldData,
	FieldDataOption,
	FreeTextFieldData,
	LicensesFieldData,
	OrganizationsFieldData,
	PublicationsFieldData,
	RadioBoxFieldData,
	RegistriesFieldData,
	ResearchersAutoCompleteFieldData,
	RichTextAreaFieldData,
	UploadFieldData,
	ServicesFieldData,
	// TableFieldData,
	TagsFieldData,
	TaxonomiesFieldData,
	TextAreaFieldData,
	ValidationFieldData,
	WordListFieldData
} from '@app/core/model/dataset-profile-definition/field-data/field-data';
import {ConfigurationService} from "@app/core/services/configuration/configuration.service";

@Component({
	selector: 'app-dataset-profile-editor-field-component',
	templateUrl: './dataset-profile-editor-field.component.html',
	styleUrls: ['./dataset-profile-editor-field.component.scss']
})
export class DatasetProfileEditorFieldComponent extends BaseComponent implements OnInit, ErrorStateMatcher {
	@Input() viewOnly: boolean;
	@Input() form: FormGroup;
	@Input() showOrdinal = true;
	@Input() indexPath: string;
	validationTypeEnum = ValidationType;
	viewStyleEnum = DatasetProfileFieldViewStyle;
	// isFieldMultiplicityEnabled = false;

	viewType: ViewStyleType;
	viewTypeEnum =  ViewStyleType;
	// private subject$:Subject<DatasetDescriptionFieldEditorModel> = new Subject<DatasetDescriptionFieldEditorModel>();



	@Input() expandView: boolean = true;
	@Input() canBeDeleted:boolean = true;

	@Output() delete = new EventEmitter<void>();


	//rdaCommonStandards = this.datasetProfileService.getRDACommonStandards(); //GK: Don't do that again. The service has a weird async behaviour.

	constructor(
		public enumUtils: EnumUtils,
		public datasetProfileService: DatasetProfileService,
		private dialog: MatDialog,
		private configurationService: ConfigurationService
	) { super();

	}


	isErrorState(control: FormControl, form: FormGroupDirective | NgForm): boolean {

		if(this.form.get('viewStyle').untouched) return false;

		return this.form.get('viewStyle').invalid;
	}

	ngOnInit() {

		// this.subject$.pipe(takeUntil(this._destroyed)).pipe(debounceTime(600)).subscribe(model=>{
		// 	this.previewForm = model.buildForm();
		// });



		// if (this.form.get('multiplicity')) {
		// 	if (this.form.get('multiplicity').value.min > 1 && this.form.get('multiplicity').value.max > 1) {
		// 		this.isFieldMultiplicityEnabled = true;
		// 	}
		// }

		const renderStyle = this.form.get('viewStyle').get('renderStyle').value;
		if(renderStyle){

			// this.matcher.setReference(this.form);
			const type = this.form.get('viewStyle').get('renderStyle').value;

			switch(type){
				case DatasetProfileFieldViewStyle.BooleanDecision:
					this.viewType = this.viewTypeEnum.BooleanDecision;
					break;
				case DatasetProfileFieldViewStyle.CheckBox:
					this.viewType = this.viewTypeEnum.CheckBox;
					break;
				case DatasetProfileFieldViewStyle.ComboBox:

					const comboType = this.form.get('data').get('type').value;
					if(comboType === DatasetProfileComboBoxType.Autocomplete){
						this.viewType = this.viewTypeEnum.Other;
					}else if(comboType === DatasetProfileComboBoxType.WordList){
						this.viewType = this.viewTypeEnum.Select;
					}
					break;
				case DatasetProfileFieldViewStyle.InternalDmpEntities:
					this.viewType = this.viewTypeEnum.InternalDmpEntities;
					break;
				case DatasetProfileFieldViewStyle.FreeText:
					this.viewType = this.viewTypeEnum.FreeText;
					break;
				case DatasetProfileFieldViewStyle.RadioBox:
					this.viewType = this.viewTypeEnum.RadioBox;
					break;
				case DatasetProfileFieldViewStyle.TextArea:
					this.viewType = this.viewTypeEnum.TextArea;
					break;
				case DatasetProfileFieldViewStyle.RichTextArea:
					this.viewType = this.viewTypeEnum.RichTextArea;
					break;
				case DatasetProfileFieldViewStyle.Upload:
					this.viewType = this.viewTypeEnum.Upload;
					break;
				case DatasetProfileFieldViewStyle.Table:
					this.viewType = this.viewTypeEnum.Table;
					break;
				case DatasetProfileFieldViewStyle.DatePicker:
					this.viewType = this.viewTypeEnum.DatePicker;
					break;
				case DatasetProfileFieldViewStyle.ExternalDatasets:
					this.viewType = this.viewTypeEnum.ExternalDatasets;
					break;
				case DatasetProfileFieldViewStyle.DataRepositories:
					this.viewType = this.viewTypeEnum.DataRepositories;
					break;
				case DatasetProfileFieldViewStyle.PubRepositories:
					this.viewType = this.viewTypeEnum.PubRepositories;
					break;
				case DatasetProfileFieldViewStyle.JournalRepositories:
					this.viewType = this.viewTypeEnum.JournalRepositories;
					break;
				case DatasetProfileFieldViewStyle.Taxonomies:
					this.viewType = this.viewTypeEnum.Taxonomies;
					break;
				case DatasetProfileFieldViewStyle.Licenses:
					this.viewType = this.viewTypeEnum.Licenses;
					break;
				case DatasetProfileFieldViewStyle.Publications:
					this.viewType = this.viewTypeEnum.Publications;
					break;
				case DatasetProfileFieldViewStyle.Registries:
					this.viewType = this.viewTypeEnum.Registries;
					break;
				case DatasetProfileFieldViewStyle.Services:
					this.viewType = this.viewTypeEnum.Services;
					break;
				case DatasetProfileFieldViewStyle.Tags:
					this.viewType = this.viewTypeEnum.Tags;
					break;
				case DatasetProfileFieldViewStyle.Researchers:
					this.viewType = this.viewTypeEnum.Researchers; //TODO RESEARCHERS
					break;
				case DatasetProfileFieldViewStyle.Organizations:
					this.viewType = this.viewTypeEnum.Organizations;
					break;
				case DatasetProfileFieldViewStyle.DatasetIdentifier:
					this.viewType = this.viewTypeEnum.DatasetIdentifier;
					break;
				case DatasetProfileFieldViewStyle.Currency:
					this.viewType = this.viewTypeEnum.Currency;
					break;
				case DatasetProfileFieldViewStyle.Validation:
					this.viewType = this.viewTypeEnum.Validation;
					break;
			}
			if(this.viewType !== this.viewTypeEnum.FreeText) {
				this.setValidator(ValidationType.URL, false);
			}
		}

		// this.showPreview = true;




		// this.addNewRule();

		// this.form.get('viewStyle').get('renderStyle').valueChanges
		// 	.pipe(takeUntil(this._destroyed))
		// 	.subscribe(x => {


		// 		// const previewStatus = this.showPreview;
		// 		//!! Important to be before the if statement
		// 		this.showPreview = false;

		// 		if (this.form.get('data')) {
		// 			this.form.removeControl('data');

		// 			switch (x) {
		// 				case DatasetProfileFieldViewStyle.BooleanDecision:
		// 					this.form.addControl('data', new BooleanDecisionFieldDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.CheckBox:
		// 					this.form.addControl('data', new CheckBoxFieldDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.ComboBox:
		// 					this.form.addControl('data', new WordListFieldDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.InternalDmpEntities:
		// 					this.form.addControl('data', new ResearchersAutoCompleteFieldDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.FreeText:
		// 					this.form.addControl('data', new FreeTextFieldDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.RadioBox:
		// 					this.form.addControl('data', new RadioBoxFieldDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.TextArea:
		// 					this.form.addControl('data', new TextAreaFieldDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.DatePicker:
		// 					this.form.addControl('data', new DatePickerDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.ExternalDatasets:
		// 					this.form.addControl('data', new ExternalDatasetsDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.DataRepositories:
		// 					this.form.addControl('data', new DataRepositoriesDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.Registries:
		// 					this.form.addControl('data', new RegistriesDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.Services:
		// 					this.form.addControl('data', new ServicesDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.Tags:
		// 					this.form.addControl('data', new TagsDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.Researchers:
		// 					this.form.addControl('data', new ResearchersDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.Organizations:
		// 					this.form.addControl('data', new OrganizationsDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.DatasetIdentifier:
		// 					this.form.addControl('data', new DatasetIdentifierDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.Currency:
		// 					this.form.addControl('data', new CurrencyDataEditorModel().buildForm());
		// 					break;
		// 				case DatasetProfileFieldViewStyle.Validation:
		// 					this.form.addControl('data', new ValidationDataEditorModel().buildForm());
		// 					break;
		// 			}
		// 		}


		// 		//reset the preview status
		// 		// this.showPreview = previewStatus;
		// 		this.showPreview = true;
		// 	});
	}

	// defaulValueRequired(viewStile: DatasetProfileFieldViewStyle): boolean {
	// 	switch (viewStile) {
	// 		case DatasetProfileFieldViewStyle.CheckBox:
	// 			return true;
	// 		case DatasetProfileFieldViewStyle.RadioBox:
	// 		case DatasetProfileFieldViewStyle.TextArea:
	// 		case DatasetProfileFieldViewStyle.FreeText:
	// 		case DatasetProfileFieldViewStyle.ComboBox:
	// 		case DatasetProfileFieldViewStyle.InternalDmpEntities:
	// 		case DatasetProfileFieldViewStyle.BooleanDecision:
	// 		case DatasetProfileFieldViewStyle.DatePicker:
	// 		case DatasetProfileFieldViewStyle.ExternalDatasets:
	// 		case DatasetProfileFieldViewStyle.DataRepositories:
	// 		case DatasetProfileFieldViewStyle.Registries:
	// 		case DatasetProfileFieldViewStyle.Services:
	// 		case DatasetProfileFieldViewStyle.Tags:
	// 		case DatasetProfileFieldViewStyle.Registries:
	// 		case DatasetProfileFieldViewStyle.Organizations:
	// 		case DatasetProfileFieldViewStyle.DatasetIdentifier:
	// 		case DatasetProfileFieldViewStyle.Currency:
	// 		case DatasetProfileFieldViewStyle.Validation:
	// 			return false;
	// 		default:
	// 			return false;
	// 	}
	// }



	// onIsFieldMultiplicityEnabledChange(isFieldMultiplicityEnabled: boolean) {
	// 	if (!isFieldMultiplicityEnabled) {
	// 		(<FormControl>this.form.get('multiplicity').get('min')).setValue(0);
	// 		(<FormControl>this.form.get('multiplicity').get('max')).setValue(0);
	// 	}
	// }

	addNewRule() {
		const rule: RuleEditorModel = new RuleEditorModel();
		(<FormArray>this.form.get('visible').get('rules')).push(rule.buildForm());
	}


	private _formChangesSubscription:Subscription;
	private _showPreview: boolean = false;

	//  get showPreview(): boolean{

	// 	return this._showPreview;
	//  }

	//  set showPreview(value:boolean){
	// 	if(value == false){//hide preview
	// 		//close subsciption
	// 		if(this._formChangesSubscription){
	// 			this._formChangesSubscription.unsubscribe();
	// 			this._formChangesSubscription = null;
	// 		}
	// 	}

	// 	if(value == true){
	// 		//value is already true
	// 		if(this._showPreview){
	// 			if(this._formChangesSubscription){
	// 				this._formChangesSubscription.unsubscribe();
	// 				this._formChangesSubscription = null;
	// 			}
	// 		}

	// 		//initialize
	// 		if(this.form.get('viewStyle').get('renderStyle').value){
	// 			this._generatePreviewForm();
	// 		}
	// 		this._formChangesSubscription = this.form.valueChanges.subscribe(()=>{
	// 			this._generatePreviewForm();
	// 		});
	// 	}
	// 	this._showPreview = value;

	//  }

	// previewForm: FormGroup;

	// private _generatePreviewForm(){

	// 	if(!this.form.get('data')){
	// 		return;
	// 	}
	// 	this.previewForm = null;
	// 	const fieldEditorModel = new DatasetDescriptionFieldEditorModel();

	// 	fieldEditorModel.viewStyle= {
	// 			renderStyle: this.form.get('viewStyle').get('renderStyle').value,
	// 			cssClass: null
	// 		};

	// 	fieldEditorModel.data = (this.form.get('data') as FormGroup).getRawValue();
	// 	fieldEditorModel.value = this.form.get('defaultValue').get('value').value;
	// 	fieldEditorModel.validationRequired = (this.form.get('validations').value as Array<ValidationType>).includes(ValidationType.Required);

	// 	if(this.form.get('viewStyle').get('renderStyle').value == DatasetProfileFieldViewStyle.CheckBox){
	// 		fieldEditorModel.value = this.form.get('defaultValue').get('value').value === 'true';
	// 	}
	// 	// if(this.form.get('viewStyle').get('renderStyle').value == DatasetProfileFieldViewStyle.Researchers){
	// 	// 	fieldEditorModel.data = new ResearchersAutoCompleteFieldDataEditorModel().buildForm().getRawValue();
	// 	// }
	// 	if(fieldEditorModel.viewStyle.renderStyle ===  DatasetProfileFieldViewStyle.Validation || (fieldEditorModel.viewStyle.renderStyle ===  DatasetProfileFieldViewStyle.DatasetIdentifier)
	// 		|| (fieldEditorModel.viewStyle.renderStyle === DatasetProfileFieldViewStyle.Tags)
	// 	){
	// 		fieldEditorModel.value = null;
	// 	}

	// 	// const myTicket = Guid.create().toString();
	// 	// this.validTicket = myTicket;
	// 	// setTimeout(() => { //TODO
	// 	// 	//user hasnt make any new change to inputs /show preview
	// 	// 	if(myTicket === this.validTicket){
	// 	// 		this.previewForm = fieldEditorModel.buildForm();
	// 	// 	}
	// 	// }, 600);

	// 	this.subject$.next(fieldEditorModel);


	// 	// setTimeout(() => {
	// 	// 	this.previewForm = fieldEditorModel.buildForm();
	// 	// });
	// };

	get canApplyVisibility():boolean{


		switch(this.viewType){
			case this.viewTypeEnum.TextArea:
			case this.viewTypeEnum.RichTextArea:
			case this.viewTypeEnum.Upload:
			case this.viewTypeEnum.FreeText:
			case this.viewTypeEnum.BooleanDecision:
			case this.viewTypeEnum.RadioBox:
			case this.viewTypeEnum.Select:
			case this.viewTypeEnum.CheckBox:
			case this.viewTypeEnum.DatePicker:
				return true;

		}


		return false;

	}

	// validTicket:string;
	// generatePreview(){
	// 	const fieldEditorModel = new DatasetDescriptionFieldEditorModel();

	// 	fieldEditorModel.viewStyle= {
	// 			renderStyle: this.form.get('viewStyle').get('renderStyle').value,
	// 			cssClass: null
	// 		};
	// 	fieldEditorModel.defaultValue = this.form.get('defaultValue').value;
	// 	switch (this.form.get('viewStyle').get('renderStyle').value) {
	// 		case DatasetProfileFieldViewStyle.TextArea:
	// 			fieldEditorModel.data = {
	// 				label: this.form.get('data').get('label').value
	// 			};
	// 			break;

	// 		default:
	// 			break;
	// 	}

	// 		// this.previewForm = fieldEditorModel.buildForm();


	// }
	onInputTypeChange(){


		const x = this.viewType;

		// this.showPreview = false;



		const field: Field = this.form.getRawValue();
		// field.defaultValue = {type:null, value: null};
		field.defaultValue = undefined;
		if(!this.canApplyVisibility){
			field.visible.rules = [];
		}



		// if (this.form.get('data')) {
		// 	this.form.removeControl('data');
		// }

		// this.form.removeControl('defaultValue');
		// const defaultValueModel = new DefaultValueEditorModel();
		// this.form.addControl('defaultValue',defaultValueModel.buildForm());

		switch (x) {
			case this.viewTypeEnum.BooleanDecision:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.BooleanDecision)
				// this.form.addControl('data', new BooleanDecisionFieldDataEditorModel().buildForm());

				const data: BooleanDecisionFieldData = {
					label:""
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.BooleanDecision;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.CheckBox:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.CheckBox)
				// this.form.addControl('data', new CheckBoxFieldDataEditorModel().buildForm());

				const data: CheckBoxFieldData = {
					label:''
				}
				const defaultValue: DefaultValue = {
					type: '',
					value: 'false'
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.CheckBox;
				field.data = data;
				field.defaultValue = defaultValue;

				break;
			}
			case this.viewTypeEnum.Select:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.ComboBox)
				// this.form.addControl('data', new WordListFieldDataEditorModel().buildForm());

				// this.form.get('data').setValidators(EditorCustomValidators.atLeastOneElementListValidator('options'));
				// this.form.get('data').updateValueAndValidity();
				const option1 = {label:'', value:''} as FieldDataOption;

				const data:WordListFieldData = {
					label:'',
					multiList:false,
					options:[option1],
					type:DatasetProfileComboBoxType.WordList
				}


				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.ComboBox;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.Other:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.ComboBox)
				// this.form.addControl('data', new AutoCompleteFieldDataEditorModel().buildForm()); //TODO SEE

				// this.form.get('data').setValidators(EditorCustomValidators.atLeastOneElementListValidator('autoCompleteSingleDataList'));
				// this.form.get('data').updateValueAndValidity();

				const data: AutoCompleteFieldData = {
					autoCompleteSingleDataList:[],
					multiAutoComplete: false,
					label:'',
					type: DatasetProfileComboBoxType.Autocomplete
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.ComboBox;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.InternalDmpEntities:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.InternalDmpEntities)
				// this.form.addControl('data', new ResearchersAutoCompleteFieldDataEditorModel().buildForm());//TODO TO SEE

				const data: DmpsAutoCompleteFieldData = {
					label:'',
					multiAutoComplete: false,
					type: DatasetProfileInternalDmpEntitiesType.Dmps
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.InternalDmpEntities;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.FreeText:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.FreeText)
				// this.form.addControl('data', new FreeTextFieldDataEditorModel().buildForm());

				const data: FreeTextFieldData = {
					label:''
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.FreeText;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.RadioBox:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.RadioBox)
				// this.form.addControl('data', new RadioBoxFieldDataEditorModel().buildForm());

				// this.form.get('data').setValidators(EditorCustomValidators.atLeastOneElementListValidator('options'));
				// this.form.get('data').updateValueAndValidity();

				const data: RadioBoxFieldData= {
					label:'',
					options: []
				}


				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.RadioBox;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.TextArea:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.TextArea)
				// this.form.addControl('data', new TextAreaFieldDataEditorModel().buildForm());

				const data: TextAreaFieldData = {
					label:''
				}


				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.TextArea;
				field.data = data;
				break;
			}
			case this.viewTypeEnum.RichTextArea:{
				const data: RichTextAreaFieldData = {
					label:''
				}


				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.RichTextArea;
				field.data = data;
				break;
			}
			case this.viewTypeEnum.Upload:{
				const data: UploadFieldData = {
					label:'',
					types: [],
					maxFileSizeInMB: this.configurationService.maxFileSizeInMB
				}
				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Upload;
				field.data = data;
				break;
			}
			// case this.viewTypeEnum.Table:{
			// 	const data: TableFieldData = {
			// 		label:'',
			// 		headers: [],
			// 		rows: []
			// 	}
			//
			//
			// 	field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Table;
			// 	field.data = data;
			// 	break;
			// }
			case this.viewTypeEnum.DatePicker:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.DatePicker)
				// this.form.addControl('data', new DatePickerDataEditorModel().buildForm());

				const data: DatePickerFieldData = {
					label:''
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.DatePicker;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.ExternalDatasets:{
				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.ExternalDatasets)
				// this.form.addControl('data', new ExternalDatasetsDataEditorModel().buildForm());

				const data: ExternalDatasetsFieldData = {
					label:'',
					multiAutoComplete: false
				}


				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.ExternalDatasets;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.DataRepositories:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.DataRepositories)
				// this.form.addControl('data', new DataRepositoriesDataEditorModel().buildForm());

				const data: DataRepositoriesFieldData = {
					label: '',
					multiAutoComplete: false
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.DataRepositories;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.PubRepositories:{

				const data: DataRepositoriesFieldData = {
					label: '',
					multiAutoComplete: false
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.PubRepositories;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.JournalRepositories:{

				const data: DataRepositoriesFieldData = {
					label: '',
					multiAutoComplete: false
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.JournalRepositories;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.Taxonomies:{

				const data: TaxonomiesFieldData = {
					label: '',
					multiAutoComplete: false
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Taxonomies;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.Licenses:{

				const data: LicensesFieldData = {
					label: '',
					multiAutoComplete: false
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Licenses;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.Publications:{

				const data: PublicationsFieldData = {
					label: '',
					multiAutoComplete: false
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Publications;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.Registries:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.Registries)
				// this.form.addControl('data', new RegistriesDataEditorModel().buildForm());

				const data:RegistriesFieldData = {
					label: '',
					multiAutoComplete: false
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Registries;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.Services:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.Services)
				// this.form.addControl('data', new ServicesDataEditorModel().buildForm());

				const data:ServicesFieldData = {
					label:'',
					multiAutoComplete: false
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Services;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.Tags:{
				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.Tags)
				// this.form.addControl('data', new TagsDataEditorModel().buildForm());

				const data: TagsFieldData = {
					label:''
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Tags;
				field.data = data;


				break;
			}
			case this.viewTypeEnum.Researchers:{

				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.Researchers)
				// // this.form.addControl('data', new ResearchersDataEditorModel().buildForm()); //TODO TO ASK
				// this.form.addControl('data', new ResearchersAutoCompleteFieldDataEditorModel().buildForm());

				// field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Researchers;

				const data : ResearchersAutoCompleteFieldData = {
					label:'',
					multiAutoComplete: false,
					type: DatasetProfileInternalDmpEntitiesType.Researchers
				}


				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Researchers;
				field.data = data;


				break;
			}
			case this.viewTypeEnum.Organizations:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.Organizations)
				// this.form.addControl('data', new OrganizationsDataEditorModel().buildForm());

				const data = {
					autoCompleteSingleDataList:[],
					label:'',
					multiAutoComplete: false,

				} as OrganizationsFieldData; //TODO

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Organizations;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.DatasetIdentifier:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.DatasetIdentifier)
				// this.form.addControl('data', new DatasetIdentifierDataEditorModel().buildForm());

				const data : DatasetIdentifierFieldData = {
					label:''
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.DatasetIdentifier;
				field.data = data;

				break;
			}
			case this.viewTypeEnum.Currency:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.Currency)
				// this.form.addControl('data', new CurrencyDataEditorModel().buildForm());

				const data: CurrencyFieldData = {
					label:''
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Currency;
				field.data = data;
				break;
			}
			case this.viewTypeEnum.Validation:{


				// this.form.get('viewStyle').get('renderStyle').setValue(DatasetProfileFieldViewStyle.Validation)
				// this.form.addControl('data', new ValidationDataEditorModel().buildForm());

				const data:ValidationFieldData = {
					label:''
				}

				field.viewStyle.renderStyle = DatasetProfileFieldViewStyle.Validation;
				field.data = data;

				break;
			}
		}

		// this.form.get('data').updateValueAndValidity();
		// this.form.get('viewStyle').get('renderStyle').updateValueAndValidity();
		// this.form.updateValueAndValidity();


		const form = (new FieldEditorModel).fromModel(field).buildForm();


		const fields = this.form.parent as FormArray;
		let index = -1;

		fields.controls.forEach((control,i)=>{
			if(this.form.get('id').value === control.get('id').value){
				index = i
			}
		});
		if(index>=0){
			fields.removeAt(index);
			fields.insert(index, form);
			this.form = form;


		}

		// setTimeout(() => { //TODO
		// 	this.showPreview = true;
		// });
	}


	toggleRequired(event:MatSlideToggleChange){
		this.setValidator(ValidationType.Required, event.checked);
	}

	toggleURL(event:MatSlideToggleChange){
		this.setValidator(ValidationType.URL, event.checked);
	}

	private setValidator(validationType: ValidationType, add: boolean) {
		let validationsControl = this.form.get('validations') as FormControl;
		let validations: Array<ValidationType> = validationsControl.value;

		if(add){
			if(!validations.includes(validationType)){
				validations.push(validationType);
				validationsControl.updateValueAndValidity();
			}
		} else{
			validationsControl.setValue(validations.filter(validator=> validator != validationType));
			validationsControl.updateValueAndValidity();
		}
		this.form.markAsDirty();//deactivate guard
	}

	get isRequired(){
		let validationsControl = this.form.get('validations') as FormControl;
		let validations: Array<ValidationType> = validationsControl.value;
		return validations.includes(ValidationType.Required);
	}

	get isURL(){
		let validationsControl = this.form.get('validations') as FormControl;
		let validations: Array<ValidationType> = validationsControl.value;
		return validations.includes(ValidationType.URL);
	}


	onDelete(){
		this.delete.emit();
	}
}
