package de.btu.openinfra.backend.db.daos;

import java.util.Locale;
import java.util.UUID;

import de.btu.openinfra.backend.db.MappingResult;
import de.btu.openinfra.backend.db.OpenInfraSchemas;
import de.btu.openinfra.backend.db.jpa.model.ValueList;
import de.btu.openinfra.backend.db.pojos.ValueListPojo;
import de.btu.openinfra.backend.exception.OpenInfraEntityException;
import de.btu.openinfra.backend.exception.OpenInfraExceptionTypes;

/**
 * This class represents the ValueListValue and is used to access the underlying
 * layer generated by JPA.
 *
 * @author <a href="http://www.b-tu.de">BTU</a> DBIS
 *
 */
public class ValueListDao extends OpenInfraDao<ValueListPojo, ValueList> {

	/**
	 * This is the required constructor which calls the super constructor and in
	 * turn creates the corresponding entity manager.
	 *
	 * @param currentProjectId the current project id (this should be null when
	 *                         the system schema is selected)
	 * @param schema           the required schema
	 */
	public ValueListDao(UUID currentProjectId, OpenInfraSchemas schema) {
		super(currentProjectId, schema, ValueList.class);
	}

	@Override
	public ValueListPojo mapToPojo(Locale locale, ValueList vl) {
	    if(vl != null) {
            ValueListPojo pojo = new ValueListPojo(vl);
            PtFreeTextDao pftDao = new PtFreeTextDao(currentProjectId, schema);

            pojo.setNames(pftDao.mapToPojo(
                    locale,
                    vl.getPtFreeText2()));
            pojo.setDescriptions(pftDao.mapToPojo(
                    locale,
                    vl.getPtFreeText1()));
            return pojo;
        } else {
            return null;
        } // end if else
	}

	@Override
	public MappingResult<ValueList> mapToModel(
			ValueListPojo pojo,
			ValueList vl) {

	    PtFreeTextDao ptfDao =
                new PtFreeTextDao(currentProjectId, schema);
        // set the description (is optional)
        if (pojo.getDescriptions() != null) {
            vl.setPtFreeText1(
                    ptfDao.getPtFreeTextModel(pojo.getDescriptions()));
        }

	    try {
            // in case the name value is empty
            if (pojo.getNames().getLocalizedStrings().get(0)
                    .getCharacterString().equals("")) {
                throw new OpenInfraEntityException(
                        OpenInfraExceptionTypes.MISSING_NAME_IN_POJO);
            }

            // set the name
            vl.setPtFreeText2(ptfDao.getPtFreeTextModel(pojo.getNames()));
	    } catch (NullPointerException npe) {
            throw new OpenInfraEntityException(
                    OpenInfraExceptionTypes.MISSING_NAME_IN_POJO);
        }

        // return the model as mapping result
        return new MappingResult<ValueList>(vl.getId(), vl);

	}

}
