/*
 *
 *  Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  WSO2 Inc. licenses this file to you under the Apache License,
 *  Version 2.0 (the "License"); you may not use this file except
 *  in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied. See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementConstants;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.ios.apns.service.PushNotificationService;
import org.wso2.carbon.device.mgt.mobile.impl.ios.config.IOSPluginConfigurations;
import org.wso2.carbon.device.mgt.mobile.impl.ios.dao.AbstractMobileDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.mobile.impl.ios.dao.impl.IOSDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.mobile.impl.ios.dao.util.MobileDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.mobile.impl.ios.enrollment.IOSEnrollmentTokenService;
import org.wso2.carbon.device.mgt.mobile.impl.ios.enrollment.IOSEnrollmentTokenServiceImpl;
import org.wso2.carbon.device.mgt.mobile.impl.ios.profile.IOSProfileService;
import org.wso2.carbon.device.mgt.mobile.impl.ios.profile.IOSProfileServiceImpl;
import org.wso2.carbon.ndatasource.core.DataSourceService;

/**
 * @scr.component name="org.wso2.carbon.device.ios.manager" immediate="true"
 * @scr.reference name="org.wso2.carbon.ndatasource"
 * interface="org.wso2.carbon.ndatasource.core.DataSourceService"
 * cardinality="1..1"
 * policy="dynamic"
 * bind="setDataSourceService"
 * unbind="unsetDataSourceService"
 * @scr.reference name="org.wso2.carbon.device.mgt.ios.apns.service"
 * interface="org.wso2.carbon.device.mgt.ios.apns.service.PushNotificationService"
 * cardinality="1..1"
 * policy="dynamic"
 * bind="setPushNotificationService"
 * unbind="unsetPushNotificationService"
 * @scr.reference name="org.wso2.carbon.device.manager"
 * interface="org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService"
 * policy="dynamic"
 * cardinality="1..n"
 * bind="setDeviceManagementService"
 * unbind="unsetDeviceManagementService"
 */
public class IOSDeviceMgtServiceComponent {

    private static final Log log = LogFactory.getLog(IOSDeviceMgtServiceComponent.class);
    private ServiceRegistration iosServiceRegRef;

    protected void activate(ComponentContext componentContext)  throws Exception {
        try {
            /* Initialize the data source configuration */
            BundleContext bundleContext = componentContext.getBundleContext();
            IOSPluginConfigurations.getInstance().initConfig();
            AbstractMobileDeviceManagementDAOFactory.init(DeviceManagementConstants.MobileDeviceTypes
                    .MOBILE_DEVICE_TYPE_IOS, IOSPluginConfigurations.getInstance().getIosDataSourceConfigurations()
                    .getIosDataSourceConfiguration());
            String setupOption = System.getProperty("setup");
            if (setupOption != null) {
                if (log.isDebugEnabled()) {
                    log.debug("-Dsetup is enabled. IOS Plugin repository schema initialization is about to begin");
                }
                try {
                    MobileDeviceManagementDAOUtil.setupMobileDeviceManagementSchema(
                            AbstractMobileDeviceManagementDAOFactory
                            .getDataSourceMap().get(DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS),
                            DeviceManagementConstants.MobileDeviceTypes.MOBILE_DEVICE_TYPE_IOS);
                } catch (IOSDeviceMgtPluginException e) {
                    log.error("Exception occurred while initializing mobile device management database schema", e);
                }
            }
//            iosServiceRegRef = bundleContext.registerService(DeviceManagementService.class.getName(),
//                    new IOSDeviceManagementService(), null);

            //Profile service.
            bundleContext.registerService(IOSProfileService.class, new IOSProfileServiceImpl(), null);

            //Enrollment token service.
            bundleContext.registerService(IOSEnrollmentTokenService.class, new IOSEnrollmentTokenServiceImpl(), null);

            if (log.isDebugEnabled()) {
                log.debug("Mobile Device Management Service Component has been successfully activated");
            }
        } catch (Throwable e) {
            log.error("Error occurred while activating Mobile Device Management Service Component", e);
        }
    }
    protected void deactivate(ComponentContext ctx) {
        if (log.isDebugEnabled()) {
            log.debug("De-activating Mobile Device Management Service Component");
        }
        try {
            if (iosServiceRegRef != null) {
                iosServiceRegRef.unregister();
            }
            if (log.isDebugEnabled()) {
                log.debug(
                        "Mobile Device Management Service Component has been successfully de-activated");
            }
        } catch (Throwable e) {
            log.error("Error occurred while de-activating Mobile Device Management bundle", e);
        }
    }

    protected void setDataSourceService(DataSourceService dataSourceService) {
        /* This is to avoid mobile device management component getting initialized before the underlying datasources
        are registered */
        if (log.isDebugEnabled()) {
            log.debug("Data source service set to mobile service component");
        }
    }

    protected void unsetDataSourceService(DataSourceService dataSourceService) {
        //do nothing
    }

    protected void setPushNotificationService(PushNotificationService pushNotificationService) {
        if (log.isDebugEnabled()) {
            log.debug("Push Notifications service set to mobile service component");
        }
        IOSDeviceMgtDataHolder.getInstance().setPushNotificationService(pushNotificationService);
    }

    protected void unsetPushNotificationService(PushNotificationService pushNotificationService) {
        IOSDeviceMgtDataHolder.getInstance().setPushNotificationService(null);
    }

    protected void setDeviceManagementService(DeviceManagementProviderService deviceManagementService) {
        if (log.isDebugEnabled()) {
            log.debug("Setting device management service provider");
        }
        IOSDeviceMgtDataHolder.getInstance().setDeviceManagementService(deviceManagementService);
    }

    protected void unsetDeviceManagementService(DeviceManagementProviderService deviceManagementService) {
        if (log.isDebugEnabled()) {
            log.debug("Removing device management service provider");
        }

        IOSDeviceMgtDataHolder.getInstance().setDeviceManagementService(null);
    }

    protected void setProfileService(IOSProfileService profileService) {
        if (log.isDebugEnabled()) {
            log.debug("Setting ios profile service provider");
        }
        IOSDeviceMgtDataHolder.getInstance().setProfileService(profileService);
    }

    protected void unsetProfileService(IOSProfileService profileService) {
        if (log.isDebugEnabled()) {
            log.debug("Removing ios profile service provider");
        }
        IOSDeviceMgtDataHolder.getInstance().setProfileService(null);
    }

    protected void setEnrollmentTokenService(IOSEnrollmentTokenService tokenService) {
        if (log.isDebugEnabled()) {
            log.debug("Setting ios enrollment token service provider");
        }
        IOSDeviceMgtDataHolder.getInstance().setTokenService(tokenService);
    }

    protected void unsetEnrollmentTokenService(IOSEnrollmentTokenService tokenService) {
        if (log.isDebugEnabled()) {
            log.debug("Removing ios enrollment token service provider");
        }
        IOSDeviceMgtDataHolder.getInstance().setTokenService(null);
    }

}
