(function(){
  "use strict";

  const Phonegap = class {
    static init(createGameClient){
      document.addEventListener("deviceready", () => {
        Phonegap.ready(createGameClient);
      }, false);
    }

    static pushNotificationError(){
      ClientUtil.error("PushNotifications register error: " + error);
      Phonegap.error("Failed to register with push notification service. Please contact support by email: matso167@gmail.com");
    }

    static pushNotificationSuccess(createGameClient){
      ClientUtil.log("pushNotificationSuccess");
      const game = createGameClient();

      document.addEventListener("pause", () => game.pause(), false);
      document.addEventListener("resume", () => game.resume(), false);
    }

    static initPushNotifications(createGameClient){
      if(typeof device !== "undefined" && device.platform === "Android"){
        PushNotifications.registerFcm((pushNotificationId) => {
          GameGlobals.fcmPushNotificationId = pushNotificationId;
          Phonegap.pushNotificationSuccess(createGameClient);
        }, Phonegap.pushNotificationError);
        return;
      }

      if(typeof device !== "undefined" && device.platform === "iOS"){
        PushNotifications.registerApn((pushNotificationId) => {
          GameGlobals.pushNotificationId = pushNotificationId;
          Phonegap.pushNotificationSuccess(createGameClient);
        }, (e) => {
          Phonegap.pushNotificationError(e);
        });
        return;
      }

      ClientUtil.log("PushNotifications: Platform (" + (typeof device === "undefined" ? "N/A" : device.platform) + ") does not implement push notifications");
      Phonegap.pushNotificationSuccess(createGameClient);
    }

    static error(error){
      navigator.splashscreen.hide();
      ClientUtil.error("Phonegap init error: " + error);
      alert(error);
    }

    static ready(createGameClient){
      if(EcmascriptSupport.testAll()){
        if(GameGlobals.notifications){
          Phonegap.initPushNotifications(createGameClient);
        }else{
          Phonegap.pushNotificationSuccess(createGameClient);
        }
      }else{
        Phonegap.error("Your browser does not meet the minimum requirements for the game");
      }
    }
  };

  window.Phonegap = Phonegap;
})();
