package org.wso2.carbon.device.mgt.ios.util;

import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.ios.api.utils.util.Message;
import org.wso2.carbon.device.mgt.ios.exception.BadRequestException;
import org.wso2.carbon.device.mgt.ios.exception.ResourceNotFoundException;
import org.wso2.carbon.device.mgt.ios.exception.ServiceImplementationException;

import javax.ws.rs.core.MediaType;

public class DeviceUtils {

    private static final String DEVICE_ID_NOT_FOUND = "Device Id not found for device found at %s";
    private static final String DEVICE_ID_SERVICE_NOT_FOUND =
            "Issue in retrieving device management service instance for device found at %s";
    private static final String COMMA_SEPARATION_PATTERN = ", ";

    public DeviceIdentifier fetchDeviceIdentifierInstance(String deviceId,
                                                          Message message, MediaType responseMediaType) {

        if (deviceId == null || deviceId.trim().isEmpty()) {
            message.setErrorMessage("Empty device id received");
            throw new BadRequestException(message, responseMediaType);
        }

        DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
        deviceIdentifier.setId(deviceId);
        deviceIdentifier.setType(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS);

        try {
            Device device = IOSServiceUtils.getDeviceManagementService().getDevice(deviceIdentifier);

            if (device == null || device.getDeviceIdentifier() == null || device.getDeviceIdentifier().isEmpty()) {
                message.setErrorMessage("Device not found for requested device id");
                throw new ResourceNotFoundException(message, responseMediaType);
            }
        } catch (DeviceManagementException e) {
            message.setErrorMessage("Issue in retrieving device management service instance");
            throw new ServiceImplementationException(message, responseMediaType);
        }

        return deviceIdentifier;
    }
}
