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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
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.apns.exception.APNSException;
import org.wso2.carbon.device.mgt.ios.apns.service.PushNotificationService;
import org.wso2.carbon.device.mgt.ios.core.publisher.TokenPersistence;
import org.wso2.carbon.device.mgt.ios.core.util.CertificateConfig;
import org.wso2.carbon.device.mgt.ios.exception.ResourceNotFoundException;
import javax.ws.rs.core.MediaType;

public class PushNotificationSenderUtils {

    private static final Log log = LogFactory.getLog(PushNotificationSenderUtils.class);

    public void contactAPNS(DeviceIdentifier deviceIdentifier, Message message)
            throws APNSException {

        Device device = null;

        try {
            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, MediaType.APPLICATION_JSON_TYPE);
            }
            TokenPersistence tokenPersistence = new TokenPersistence();
            PushNotificationService pushNotificationService =
                    IOSServiceUtils.getPushNotificationService();
            pushNotificationService.sendMDMNotification(CertificateConfig.getMDMPem(),
                                                        CertificateConfig.getMDMPassword(),
                                                        CertificateConfig.isProductionMDM(),
                                                        tokenPersistence.getPropertyValue(device.getProperties(),
                                                                                          TokenPersistence.MDM_TOKEN),
                                                        tokenPersistence.getPropertyValue(device.getProperties(),
                                                                                          TokenPersistence.MAGIC_TOKEN)
            );

        } catch (DeviceManagementException e) {
            log.error("Error occurred when retrieving device information", e);
        }
    }
}
