package jp.odakyu.toiletsignage.application;

import android.app.ActivityManager;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import java.util.List;
import java.util.Timer;

import jp.odakyu.toiletsignage.activity.MainActivity;
import jp.odakyu.toiletsignage.task.UpdateToiletInfoTask;

/**
 * Created by agentec on 2017/12/13.
 */

public class ToiletApplication extends Application {
    private final String TAG = "ToiletApplication";

    private Timer updateToiletInfoTimer;

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public synchronized void stopTimer() {
        Log.i(TAG, "stopTimer");
        if (updateToiletInfoTimer != null) {
            Log.i(TAG, "stopTimer STOP");
            updateToiletInfoTimer.cancel();
            updateToiletInfoTimer = null;
        }
    }

    public synchronized void startTimer() {
        Log.i(TAG, "startTimer");
        if (updateToiletInfoTimer == null) {
            Log.i(TAG, "startTimer Start");
            updateToiletInfoTimer = new Timer();
            // スケジュール開始と同時にすぐ新着更新を開始する
            int interval = 10000; //10秒
            updateToiletInfoTimer.schedule(new UpdateToiletInfoTask(this), 0, interval);
        }
    }

    public boolean isForeground(Context context) {
        ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        assert am != null;
        List<ActivityManager.RunningAppProcessInfo> processInfoList = am.getRunningAppProcesses();
        boolean isForeground = false;
        for( ActivityManager.RunningAppProcessInfo info : processInfoList){
            if(info.processName.equals(getPackageName())){
                if( info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
                    isForeground = true;
                    break;
                    // ここにフォアグラウンドの場合の処理を実装
                }
            }
        }
        return isForeground;
    }
}
