package network;

import backupAndRecovery.*;
import org.dom4j.*;

/**
 * Library for backup protocol. Methods required to parse and build backup
 * requests and responses are provided.
 *
 * All messages are expected to be in XML format.
 *
 * @author Marcel Duris
 */
public class ProtocolBackup {

    /**
     * Parses request received over network. This method returns metadata of
     * file, which is requested to be backed up.
     * 
     * @param msg Document of message received.
     * @return BackupMetaContainer of file to be backed up
     * @throws IllegalArgumentException if request is in invalid format
     */
    public static BackupMetaContainer parseRequest(Document msg) throws IllegalArgumentException {
        if (msg.getRootElement().getName().compareTo("backupRequest") != 0)
            throw new IllegalArgumentException();

        BackupMetaContainer meta = new BackupMetaContainer(msg.getRootElement().element("backup"));
        return meta;
    }

    /**
     * Given metadata of file to be backed up, this method creates request
     * which can be send to other networked peers.
     * 
     * @param meta data of file going to be backed up
     * @return byte array to be placed directly into UDP packet
     */
    public static byte[] createRequest(BackupMetaContainer meta) {

        Document metaXml = meta.getXmlDocument();
        Element root = metaXml.getRootElement();

        Document request = DocumentHelper.createDocument();
        Element reqRoot = request.addElement("backupRequest");
        reqRoot.add(root);

        return request.asXML().getBytes();
    }
}
