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

import org.wso2.carbon.device.mgt.ios.payload.beans.Domain;
import org.wso2.carbon.device.mgt.ios.payload.beans.PayloadOperation;
import org.wso2.carbon.device.mgt.ios.payload.dto.PayloadOperationWrapper;
import org.wso2.carbon.device.mgt.ios.payload.dto.PayloadProperties;
import org.wso2.carbon.device.mgt.ios.payload.exception.PListException;
import org.wso2.carbon.device.mgt.ios.payload.exception.ProfileConfigurationException;
import org.wso2.carbon.device.mgt.ios.payload.util.OperationUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DomainOperations {

    private static final String PAYLOAD_DISPLAY_NAME = "Domain Configurations";
    private static final String PAYLOAD_DESCRIPTION = "Domain Configurations for %s";
    private static final String EMAIL_DOMAINS = "EmailDomains";
    private static final String WEB_DOMAINS = "WebDomains";

    public PayloadOperationWrapper createDomainPayload(Domain domain) throws PListException,
            ProfileConfigurationException {

        PayloadProperties payloadProperties = generateCommonDomainElements(domain,
                OperationUtils.getTenantNameFromOperationID(), OperationUtils.isPayloadRemoveDisallowedForTenant());

        domain.validateRequest();

        Map<String, Object> domainMap = domain.getCommandMap();

        domainMap.put(EMAIL_DOMAINS, domain.getEmailDomains());
        domainMap.put(WEB_DOMAINS, domain.getWebDomains());

        List<Object> payloadContent = new ArrayList();
        payloadContent.add(domainMap);

        PayloadOperationWrapper payloadOperationWrapper = new PayloadOperationWrapper();
        payloadOperationWrapper.setPayload(payloadContent);
        payloadOperationWrapper.setPayloadProperties(payloadProperties);

        return payloadOperationWrapper;
    }

    private PayloadProperties generateCommonDomainElements(Domain domain, String tenantName,
                                                        boolean payloadRemoveDisallowed) {

        PayloadProperties payloadProperties = new PayloadProperties();
        payloadProperties.setTenantName(tenantName);
        payloadProperties.setPayloadType(PayloadOperation.PayloadType.DOMAIN.getPayloadType());
        payloadProperties.setPayloadIdentifier(domain.getUUID());
        payloadProperties.setPayloadDisplayName(PAYLOAD_DISPLAY_NAME);
        payloadProperties.setPayloadDescription(String.format(PAYLOAD_DESCRIPTION, tenantName));
        payloadProperties.setPayloadRemoveDisallowed(payloadRemoveDisallowed);

        domain.populateCommandPayloadElements(payloadProperties);

        return payloadProperties;
    }
}
