package ch.threema.app.jobs;

import android.app.job.JobParameters;
import android.app.job.JobService;

import androidx.work.Configuration;

import org.slf4j.Logger;

import ch.threema.app.services.PollingHelper;
import static ch.threema.base.utils.LoggingKt.getThreemaLogger;

import static ch.threema.app.di.DIJavaCompat.getMasterKeyManager;

public class ReConnectJobService extends JobService {
    private static final Logger logger = getThreemaLogger("ReConnectJobService");
    private static boolean isStopped;
    private PollingHelper pollingHelper = null;

    public ReConnectJobService() {
        new Configuration.Builder().setJobSchedulerJobIdRange(20000, 21000).build();
    }

    @Override
    public boolean onStartJob(final JobParameters jobParameters) {
        logger.info("Reconnect job {} started", jobParameters.getJobId());

        isStopped = false;

        new Thread(new Runnable() {
            @Override
            public void run() {
                logger.info("Scheduling poll on reconnect");

                if (pollingHelper == null) {
                    pollingHelper = new PollingHelper(ReConnectJobService.this, "reconnectJobService");
                }

                if (!isStopped) {
                    boolean success = pollingHelper.poll(true) || getMasterKeyManager().isLocked();

                    if (!isStopped) {
                        try {
                            jobFinished(jobParameters, !success);
                            logger.info("Reconnect job {} finished. Success = {}", jobParameters.getJobId(), success);
                        } catch (Exception e) {
                            logger.error("Exception while finishing ReConnectJob", e);
                        }
                    }
                }
            }
        }, "ReConnectJobService").start();

        return true;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        isStopped = true;
        logger.info("Reconnect job {} stopped", jobParameters.getJobId());

        return false;
    }
}
