package jp.odakyu.toiletsignage.application;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.util.List;
import java.util.Timer;

import jp.odakyu.toiletsignage.log.Logger;
import jp.odakyu.toiletsignage.task.UpdateToiletInfoTask;
import jp.odakyu.toiletsignage.util.FileUtil;

import static jp.odakyu.toiletsignage.constants.ToiletConstants.APP_LOG_PATH;

/**
 * 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();
        Logger logger = new Logger();
        File downloadFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        String logPath = downloadFilePath.getPath() + "/" + APP_LOG_PATH;
        logger.setLogPathFormat(logPath);
        Logger.i(TAG, "onCreate");
    }

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

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

    public Timer getUpdateToiletInfoTimer() {
        return updateToiletInfoTimer;
    }
    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;
    }
}
