package it.mice.voila.runtime.springmvc.csrf;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

public class SecuritySessionBean implements Serializable { 

	/**
	 * 
	 */
	private static final long serialVersionUID = -6539168343340594151L;

	private Map<String, FormField> formFields;
	
	public SecuritySessionBean() {
		super();
		this.formFields = new HashMap<String, FormField>();
	}
	
	public Map<String, FormField> getFormFields() {
		return formFields;
	}

	public void setFormFields(Map<String, FormField> formFields) {
		this.formFields = formFields;
	}

	public FormField addSubmitFormField(String name, String value) {
		FormField ff = addFormField(name, value, "submit");
		String[] parts = name.split("\\?");
		//addFormField(parts[0], value, "submit");
		for (int i = 1; i < parts.length; i++) {
			String[] subParts = parts[i].split("=");
			addFormField(subParts[0], subParts[1], "hidden");
		}
		
		return ff;
	}

	public FormField addDeleteFlagFormField(String name) {
		String fieldName = name + "DeleteFlag";
		FormField ff = addFormField(fieldName, "true", "check");
		ff.getParameterValue().add("false");
		
		return ff;
	}

	public FormField addFormField(String name, String value, String type) {
		FormField ff = formFields.get(name);
		if (ff == null) {
			ff = new FormField(name, type, !isEditable(type));
			formFields.put(name, ff);
		}
		ff.getParameterValue().add(value);
		
		return ff;
	}
	
	private boolean isEditable(String type) {
		return "text".equals(type) || "textarea".equals(type) || "password".equals(type);
	}

	public FormField setReadOnly(String name, boolean readonly, String value) {
		return setReadOnly(name, readonly, value, null);
	}

	public FormField setReadOnly(String name, boolean readonly, String value, Object actualValue) {
		FormField ff = formFields.get(name);
		if (ff != null) {
			ff.setReadonly(readonly);
			if (readonly) {
				ff.leaveOnlyThisValue(value);
				ff.setActualValue(actualValue);
			} else {
				if (isEditable(ff.getParameterType())) {
					ff.getParameterValue().clear();
				}
			}
		}
		return ff;
	}

	@Override
	public String toString() {
		return "SecuritySessionBean [formFields=" + formFields + "]";
	}
	
}
