package org.wso2.carbon.device.mgt.ios.payload.operation;

import org.apache.commons.codec.binary.Base64;
import org.wso2.carbon.device.mgt.ios.payload.exception.PListException;
import org.wso2.carbon.device.mgt.ios.payload.plist.PListGenerator;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class InstallProfileOperation {

    private static final String INSTALL_PROFILE = "InstallProfile";
    private static final String PAYLOAD = "Payload";
    public static final String PAYLOAD_PLACEHOLDER = "{PAYLOAD_PLACEHOLDER}";
    public static final String PAYLOAD_PLACEHOLDER_REPLACE_TEXT = "<string>{PAYLOAD_PLACEHOLDER}</string>";
    public static final String PAYLOAD_PLACEHOLDER_REPLACE_DATA = "<data>%s</data>";
    public static final String UTF_8 = "UTF-8";

    public String getInstallProfilePayload(String UUID, byte[] signedData)
            throws PListException, UnsupportedEncodingException {

        Map<String, Object> commandMap = new HashMap<String, Object>();
        commandMap.put(OperationPayloadConstants.REQUEST_TYPE, INSTALL_PROFILE);
        commandMap.put(PAYLOAD, PAYLOAD_PLACEHOLDER);

        Map<String, Object> payloadMap = new HashMap<String, Object>();
        payloadMap.put(OperationPayloadConstants.COMMAND, commandMap);
        payloadMap.put(OperationPayloadConstants.COMMAND_UUID, UUID);

        String payload = new PListGenerator().generatePayload(payloadMap);

        //TODO implement this in DOM level. Remove placeholder replacement later.
        return payload.replace(InstallProfileOperation.PAYLOAD_PLACEHOLDER_REPLACE_TEXT,
                String.format(PAYLOAD_PLACEHOLDER_REPLACE_DATA, new String(Base64.encodeBase64(signedData), UTF_8)));
    }

}
