package jp.odakyu.toiletsignage.application;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.util.Log;
import java.util.List;
import java.util.Timer;
import jp.odakyu.toiletsignage.task.UpdateToiletInfoTask;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;

/**
 * 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();
    }

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

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

    public void startTimer() {
        settingToiletUpdateTimer();
    }

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