/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fp.general.templates.save;

import com.fp.dto.rules.TransactionRule;
import com.fp.dto.save.SaveRequest;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.pgeneral.message.TgeneMessageTemplatesDesc;
import com.fp.persistence.pgeneral.message.TgeneMessageTemplatesDescKey;
import java.util.List;

/**
 *
 * @author BPTWPA
 */
public class SaveTemplatesDesc extends TransactionRule {

    @Override
    public SaveRequest normalProcess(SaveRequest pSaveRequest) throws Exception {
    		if(pSaveRequest.isJsf()){
    			return pSaveRequest;
    		}
            Integer code = pSaveRequest.getInteger("code");
            String languaje =pSaveRequest.getString("languaje");
            String description=pSaveRequest.getString("description");
            String template=pSaveRequest.getString("template");
            String remove=pSaveRequest.getString("remove");
            
            TgeneMessageTemplatesDesc templatesDesc=TgeneMessageTemplatesDesc.find(
                    PersistenceHelper.getEntityManager(), new TgeneMessageTemplatesDescKey(code, languaje));
            if(remove!=null && remove.compareTo("remove")==0){
                PersistenceHelper.delete(templatesDesc);
            }else{
            if(templatesDesc!=null){
                templatesDesc.setDescription(description);
                templatesDesc.setTemplate(this.replaceCharacter(template));
                PersistenceHelper.update(templatesDesc);
            }else{
                TgeneMessageTemplatesDesc templates= new TgeneMessageTemplatesDesc();
                templates.setPk(new TgeneMessageTemplatesDescKey(code, languaje));
                templates.setDescription(description);
                templates.setTemplate(template);
                PersistenceHelper.save(templates);
            }
            }
        return pSaveRequest;
    }

    @Override
    public SaveRequest reverseProcess(SaveRequest pSaveRequest) throws Exception {
        return pSaveRequest;
    }
    private String replaceCharacter(String content){
        content = content.replaceAll("Ñ","&Ntilde;");
        content = content.replaceAll("ñ","&ntilde;");
        content = content.replaceAll("Á","&Aacute;");
        content = content.replaceAll("É","&Eacute;");
        content = content.replaceAll("Í","&Iacute;");
        content = content.replaceAll("Ó","&Oacute;");
        content = content.replaceAll("Ú","&Uacute;");
        content = content.replaceAll("á","&aacute;");
        content = content.replaceAll("é","&eacute;");
        content = content.replaceAll("í","&iacute;");
        content = content.replaceAll("ó","&oacute;");
        content = content.replaceAll("ú","&uacute;");
        return content;
    }
}
