/*
 * Copyright
 *   2010 axYus - www.axyus.com
 *   2010 C.Marchand - christophe.marchand@axyus.com
 *
 * This file is part of XEMELIOS.
 *
 * XEMELIOS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * XEMELIOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package fr.gouv.finances.cp.xemelios.controls.processors;

import fr.gouv.finances.cp.xemelios.controls.models.ParamModel;
import fr.gouv.finances.cp.xemelios.controls.processors.Processor.EVENT;
import fr.gouv.finances.cp.xemelios.controls.processors.impl.IdGenerator;
import fr.gouv.finances.dgfip.utils.xml.XmlAttributesImpl;
import java.util.List;
import org.apache.log4j.Logger;


/**
 * A processor, used by control engines
 * @author cmarchand
 */
public class IdGeneratorProcessor extends AbstractProcessor {
    private static final Logger logger = Logger.getLogger(IdGeneratorProcessor.class);
    private IdGenerator idGenerator = null;

    public IdGeneratorProcessor() {
        super();
    }

    @Override
    public void setParameters(List<ParamModel> params) {
        super.setParameters(params);
        try {
            Class clazz = Class.forName((String)getParamByName("generator").getValue());
            idGenerator = (IdGenerator)(clazz.newInstance());
        } catch(Throwable t) {
            logger.fatal("instanciating IdGenerator",t);
        }
    }

    public void process(EVENT evt, String uri, String localName, String qName, XmlAttributesImpl atts) {
        String attributeName = getParamByName("generated.attribute").getValue().toString();
        String targetUri = null;
        String targetLocalName = null;
        String targetQName = null;
        int pos = -1;
        if((pos=attributeName.indexOf(":")) >= 0) {
            String prefix = attributeName.substring(0,pos);
            targetLocalName = attributeName.substring(pos+1);
            targetUri = getNamespaceContext().getNamespaceURI(prefix);
            targetQName = getNamespaceContext().getPrefix(targetUri)+":"+targetLocalName;
        } else {
            targetLocalName = targetLocalName = attributeName;
        }
        atts.addAttribute(targetUri, targetLocalName, targetQName, "CDATA", idGenerator.generateId());
    }



}