/*
 * ICESOFT COMMERCIAL SOURCE CODE LICENSE V 1.1
 *
 * The contents of this file are subject to the ICEsoft Commercial Source
 * Code License Agreement V1.1 (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.icesoft.com/license/commercial-source-v1.1.html
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations under
 * the License.
 *
 * Copyright 2009-2015 ICEsoft Technologies Canada, Corp. All Rights Reserved.
 */

package com.icesoft.icepush;

import net.rim.pushsdk.commons.IdGenerator;
import net.rim.pushsdk.commons.IdGeneratorImpl;
import net.rim.pushsdk.commons.PushSDKException;
import net.rim.pushsdk.commons.PushSDKPropertiesImpl;
import net.rim.pushsdk.commons.UnauthorizedException;
import net.rim.pushsdk.commons.content.Content;
import net.rim.pushsdk.commons.content.TextContent;
import net.rim.pushsdk.commons.http.HttpClient;
import net.rim.pushsdk.commons.http.HttpClientImpl;
import net.rim.pushsdk.pap.PapService;
import net.rim.pushsdk.pap.PapServiceImpl;
import net.rim.pushsdk.pap.control.PushMessageControl;
import net.rim.pushsdk.pap.control.StatusQueryMessageControl;
import net.rim.pushsdk.pap.unmarshal.BadMessageException;
import net.rim.pushsdk.pap.unmarshal.PushResponse;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import net.rim.pushsdk.pap.unmarshal.StatusQueryResponse;
import org.icepush.NotificationProvider;
import org.icepush.OutOfBandNotifier;
import org.icepush.PushNotification;
import org.icepush.util.ExtensionRegistry;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import java.util.logging.Level;

/**
 * Implementation of Blackberry push service notification provider
 */
public class BPNSNotificationProvider implements NotificationProvider {

    private static String pushAppId;
    private static String pushAppPassword;
    private static String APPLICATION_CREDENTIALS_PROPERTY="org.icemobile.blackberry.applicationCredentials";
    private static final Logger log = Logger.getLogger(BPNSNotificationProvider.class.getName());
    OutOfBandNotifier outOfBandNotifier;


    public BPNSNotificationProvider() {
        log.info("BPNS Notification Provider is off: appId = " + pushAppId );
    }


    public void send( String uri, PushNotification notification ) {

        IdGenerator idGenerator = new IdGeneratorImpl();

        // Addresses refers to list of recipients. Group notification can only be done
        // through Balackberry Enterprise Server
        List<String> addresses = new ArrayList<String>();
        int spos = uri.indexOf(":");
        if (spos > -1) {
            addresses.add( uri.substring(spos+1));
        }

        PushMessageControl pushMessageControl = new
                PushMessageControl(idGenerator, pushAppId, addresses);

        Content papContent = new TextContent("subject: " + notification.getSubject() +
                                             ", message: " + notification.getDetail());


        log.finest("PushControlMessage: " + pushMessageControl.toString() );

        // THis is the version without the PapBeanLocator.
        PushSDKPropertiesImpl properties = new PushSDKPropertiesImpl();

        HttpClient client = new HttpClientImpl();
        ((HttpClientImpl)client).setPushSDKProperties(properties);

        PapService papService = new PapServiceImpl();

        papService.setHttpClient(client);
        papService.setPushSDKProperties(properties);


        PushResponse response = null;
        String pushId = null;
        try {

            response = papService.push(pushAppId, pushAppPassword, pushAppId, pushMessageControl, papContent);
            pushId = response.getPushId();

            log.fine("BPNS Push Notification sent, pushId = " + pushId + ", response = " + response);
            outOfBandNotifier.trace("BPNS Push Notification sent, pushId = " + pushId + ", response = " + response);

        } catch (Exception e) {
            log.log(Level.SEVERE, "Exception sending BPNS push: ", e);
            outOfBandNotifier.trace("Exception sending BPNS push: " + e);
        }


        if (pushId != null) {
            StatusQueryMessageControl statusQueryControl = new StatusQueryMessageControl(
                    pushId, addresses
            );

            try {

                log.finest("BPNS - Sending status query...");
                StatusQueryResponse queryResponse = papService.statusQuery(
                        pushAppId, pushAppPassword, statusQueryControl );
                log.finest("BPNS - Status Query Response: " + queryResponse);

            }  catch (BadMessageException bme) {
                log.severe("BPNS - Exception querying status: " + bme);
            } catch (UnauthorizedException ue) {
                log.severe("BPNS - Unauthorized Exception: " + ue);
            } catch (PushSDKException pse) {
                log.severe("BPNS - PushSDKException: " + pse);
            }
        } else {
            log.warning("BPNS No PushId response");
        }
    }

    public void registerWith(OutOfBandNotifier outOfBandNotifier) {
        outOfBandNotifier.registerProvider("bpns", this);
        this.outOfBandNotifier = outOfBandNotifier;
     }

    public static class AutoRegister implements ServletContextListener {
        //private logger required to avoid instantiating outer class
        //just for logging ClassNotFound
        private static final Logger log = Logger.getLogger(
                AutoRegister.class.getName());
        public void contextInitialized(ServletContextEvent servletContextEvent) {


            try {
                String pushAppCredentials = System.getProperty(APPLICATION_CREDENTIALS_PROPERTY, "");
                if ( (null == pushAppCredentials) || "".equals(pushAppCredentials) )  {
                    pushAppCredentials = servletContextEvent.getServletContext()
                            .getInitParameter(APPLICATION_CREDENTIALS_PROPERTY);
                }

                int spos = pushAppCredentials.indexOf (":");
                if (spos > -1) {
                    pushAppId = pushAppCredentials.substring(0, spos);
                    pushAppPassword = pushAppCredentials.substring(spos+1).trim();

                    ExtensionRegistry
                            .addExtension(servletContextEvent.getServletContext(), 5,
                                          NotificationProvider.class.getName(),
                                          new BPNSNotificationProvider());
                } else {
                    log.log(Level.INFO, "BPNS Notification Provider is off");
                    log.log(Level.FINE, "reason: Missing credentials");
                }
            } catch (NoClassDefFoundError t) {
                log.log(Level.INFO, "BPNS Notification Provider is off");
                log.log(Level.FINE, "reason: RIM pushsdk classes not available");
            } catch (Throwable t) {
                log.log(Level.INFO, "BPNS Notification Provider is off");
                log.log(Level.FINE, "reason: Could not read BPNS configuration during Registration", t);
            }
        }

        public void contextDestroyed(ServletContextEvent servletContextEvent) {
            //To change body of implemented methods use File | Settings | File Templates.
        }
    }
}
