package org.wso2.carbon.device.mgt.mobile.impl.ios.apns;

import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.push.notification.NotificationContext;
import org.wso2.carbon.device.mgt.common.push.notification.NotificationStrategy;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationExecutionFailedException;
import org.wso2.carbon.device.mgt.ios.apns.exception.APNSException;
import org.wso2.carbon.device.mgt.ios.core.util.CertificateConfig;
import org.wso2.carbon.device.mgt.mobile.impl.ios.internal.IOSDeviceMgtDataHolder;
import org.wso2.carbon.device.mgt.mobile.impl.ios.util.IOSPluginConstants;
import org.wso2.carbon.device.mgt.mobile.impl.ios.util.IOSUtils;

import java.io.IOException;

/**
 * Implements the PushNotificationStrategy for APNS.
 */
public class APNSPushNotificationStrategy implements NotificationStrategy {

    private PushNotificationConfig config;

    public APNSPushNotificationStrategy(PushNotificationConfig config) {
        this.config = config;
    }

    @Override
    public void init() {
        //do nothing
    }

    @Override
    public void execute(NotificationContext notificationContext) throws PushNotificationExecutionFailedException {
        try {
            Device device =
                    IOSDeviceMgtDataHolder.getInstance().getDeviceManagementService().
                            getDevice(notificationContext.getDeviceId());
            if (IOSPluginConstants.IOS.equals(device.getType())) {
                IOSDeviceMgtDataHolder.getInstance().getPushNotificationService().
                        sendMDMNotification(CertificateConfig.getMDMPem(), CertificateConfig.getMDMPassword(),
                                CertificateConfig.isProductionMDM(), IOSUtils.getPropertyValue(device.getProperties(),
                                        IOSPluginConstants.MDM_TOKEN), IOSUtils.getPropertyValue(device.getProperties(),
                                        IOSPluginConstants.MAGIC_TOKEN));
            }
        } catch (DeviceManagementException e) {
            throw new PushNotificationExecutionFailedException("Error occurred while retrieving ios device information", e);
        }  catch (APNSException e) {
            throw new PushNotificationExecutionFailedException("Error occurred while sending the APNS message", e);
        }
    }

    @Override
    public NotificationContext buildContext() {
        return null;
    }

    @Override
    public void undeploy() {
        //do nothing
    }

    @Override
    public PushNotificationConfig getConfig() {
        return config;
    }


}