/**
 * Copyright (c) 2007-2012 EBM WebSourcing, 2012-2013 Linagora
 * 
 * This program/library is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 2.1 of the License, or (at your
 * option) any later version.
 * 
 * This program/library 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 Lesser General Public License
 * for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program/library; If not, see <http://www.gnu.org/licenses/>
 * for the GNU Lesser General Public License version 2.1.
 */
package org.ow2.petals.bc.ftp;

import java.util.Arrays;
import java.util.List;

import javax.jbi.messaging.Fault;
import javax.jbi.messaging.MessagingException;
import javax.xml.namespace.QName;

import org.ow2.petals.component.framework.api.Message.MEPConstants;
import org.ow2.petals.component.framework.api.exception.PEtALSCDKException;
import org.ow2.petals.component.framework.api.message.Exchange;
import org.ow2.petals.component.framework.util.MtomUtil;
import org.ow2.petals.component.framework.util.SourceUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import com.ebmwebsourcing.easycommons.xml.DocumentBuilders;

/**
 * @author Adrien LOUIS - EBM WebSourcing
 * @author Mathieu CARROLLE - EBM WebSourcing
 */
public class FTPUtil {

    /***
     * Build a message to indicate the mep available for this operation. TODO :
     * Move it in the cdk api.
     * 
     * @param operation
     *            operation name
     * @param mep
     *            allowed MEP
     * @return
     */
    public static String getOperationValidMep(String operation, MEPConstants... mep) {
        StringBuilder builder = new StringBuilder();
        builder.append("Exchange pattern for the " + operation.toUpperCase()
                + " operation must be ");
        for (int i = 0; i < mep.length; i++) {
            if (i > 0)
                builder.append(" or ");
            builder.append(mep[i]);
        }
        return builder.toString();
    }

    /**
     * generates the XML representation of the file name list
     * 
     * @param names
     * @return
     */
    public static String generateFileNameList(final List<String> names, final QName operation) {
        final StringBuffer result = new StringBuffer();
        result.append("<tns:" + operation.getLocalPart() + "Response xmlns:tns='");
        result.append(operation.getNamespaceURI());
        result.append("'>");
        for (final String string : names) {
            result.append("<tns:filename>");
            result.append(string);
            result.append("</tns:filename>");
        }
        result.append("</tns:" + operation.getLocalPart() + "Response>");
        return result.toString();
    }

    /**
     * Generate a MTOM response for a list of files.
     * 
     * @param names
     * @param operation
     * @return
     */
    public static Document generateMTOMListResponse(final List<String> names, final QName operation) {
        Document doc = DocumentBuilders.newDocument();
        
        Element root = doc.createElementNS(operation.getNamespaceURI(),
                "tns:" + operation.getLocalPart() + "Response");
        root.appendChild(MtomUtil.generateMtomStructure(doc, names,
                new QName(operation.getNamespaceURI(), "attachments", "tns"),
                new QName(operation.getNamespaceURI(), "filename", "tns")));
        doc.appendChild(root);
        
        return doc;
    }

    /***
     * Generate a MTOM response for a single file.
     * 
     * @param names
     * @param operation
     * @return
     */
    public static Document generateMTOMResponse(String names, QName operation) {
        Document doc = DocumentBuilders.newDocument();
        
        Element root = doc.createElementNS(operation.getNamespaceURI(),
                "tns:" + operation.getLocalPart() + "Response");
        root.appendChild(MtomUtil.generateMtomStructure(doc, Arrays.asList(names), new QName(
                operation.getNamespaceURI(), "attachment", "tns"),
                new QName(operation.getNamespaceURI(), "filename", "tns")));
        doc.appendChild(root);
        
        return doc;
    }

    public static void setIOFaultOnExchange(Exchange exchange, String ioMessage)
            throws MessagingException {
        final StringBuffer faultMessage = new StringBuffer();
        faultMessage.append("<tns:ioFault xmlns:tns='");
        faultMessage.append(exchange.getOperation().getNamespaceURI());
        faultMessage.append("'><tns:message>");
        faultMessage.append(ioMessage);
        faultMessage.append("</tns:message></tns:ioFault>");
        Fault fault = exchange.createFault();

        try {
            fault.setContent(SourceUtil.createSource(faultMessage.toString()));
            exchange.setFault(fault);
        } catch (PEtALSCDKException e) {
            throw new MessagingException(e.getMessage());
        }
    }

    public static void setMissingElementFaultOnExchange(Exchange exchange, String missingElement)
            throws MessagingException {
        final StringBuffer faultMessage = new StringBuffer();
        faultMessage.append("<tns:missingElementFault xmlns:tns='");
        faultMessage.append(exchange.getOperation().getNamespaceURI());
        faultMessage.append("'><tns:element>");
        faultMessage.append(missingElement);
        faultMessage.append("</tns:element></tns:missingElementFault>");
        Fault fault = exchange.createFault();
        try {
            fault.setContent(SourceUtil.createSource(faultMessage.toString()));
            exchange.setFault(fault);
        } catch (PEtALSCDKException e) {
            throw new MessagingException(e.getMessage());
        }
    }
}
