package com.tencent.qcloud.rntimpush;

import android.app.Application;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import com.tencent.qcloud.tuicore.TUIConstants;
import com.tencent.qcloud.tuicore.TUICore;
import com.tencent.qcloud.tuicore.interfaces.ITUINotification;

public class TencentCloudPushApplication extends Application {
  private String TAG = "TencentCloudPushApplication";

  @Override
  public void onCreate() {
    super.onCreate();
    Log.i(TAG, "onCreate");
    registerEvent();
  }

  public void registerEvent() {
    Log.i(TAG, "registerEvent");
    TUICore.registerEvent(TUIConstants.TIMPush.EVENT_NOTIFY, TUIConstants.TIMPush.EVENT_NOTIFY_NOTIFICATION, new ITUINotification() {
      @Override
      public void onNotifyEvent(String key, String subKey, Map<String, Object> param) {
        Log.i(TAG, "onNotifyEvent key:" + key + " subKey:" + subKey);
        launchMainActivity();
        if (TUIConstants.TIMPush.EVENT_NOTIFY.equals(key)) {
          if (TUIConstants.TIMPush.EVENT_NOTIFY_NOTIFICATION.equals(subKey)) {
            if (param != null) {
              String extString = (String) param.get(TUIConstants.TUIOfflinePush.NOTIFICATION_EXT_KEY);
              Log.i(TAG, "extString:" + extString);
              scheduleCheckPluginInstanceAndNotify(extString);
            }
          }
        }
      }
    });
  }

  private void launchMainActivity() {
    Intent intentLaunchMain = this.getPackageManager().getLaunchIntentForPackage(this.getPackageName());
    if (intentLaunchMain != null) {
      this.startActivity(intentLaunchMain);
    } else {
      Log.e(TAG, "Failed to get launch intent for package: " + this.getPackageName());
    }
  }
  

  private void scheduleCheckPluginInstanceAndNotify(final String extString) {
    final Handler handler = new Handler(Looper.getMainLooper());
    Timer timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {
      @Override
      public void run() {
        handler.post(new Runnable() {
          @Override
          public void run() {
            try {
              Log.i(TAG, "Checking instance: " + String.valueOf(TencentCloudPushModule.instance != null));

              if (TencentCloudPushModule.instance != null) {
                TencentCloudPushModule.instance.storeExtInfo(extString);
                timer.cancel();
              }
            } catch (Exception e) {
              Log.e(TAG, e.toString());
            }
          }
        });
      }
    }, 100, 500);
  }
}
