package com.atlassian.stash.internal.scm.git.analytics;

import com.atlassian.event.api.EventPublisher;
import com.atlassian.scheduler.*;
import com.atlassian.scheduler.config.*;
import com.atlassian.bitbucket.scm.git.GitScmConfig;

import java.util.Date;
import java.util.concurrent.TimeUnit;

public class GitAnalyticsJob {
    private static final JobId INFORMATION_ANALYTICS_JOB_ID = JobId.of(GitAnalyticsJobRunner.class.getSimpleName());
    private static final JobRunnerKey INFORMATION_ANALYTICS_JOB_RUNNER_KEY = JobRunnerKey.of(GitAnalyticsJobRunner.class.getName());

    private GitScmConfig config;
    private EventPublisher eventPublisher;
    private SchedulerService schedulerService;

    public GitAnalyticsJob(GitScmConfig config, EventPublisher eventPublisher, SchedulerService schedulerService) {
        this.config = config;
        this.eventPublisher = eventPublisher;
        this.schedulerService = schedulerService;
    }

    public void init() throws Exception {
        scheduleJob();
    }

    public void destroy() {
        unscheduleJob();
    }

    private void scheduleJob() throws SchedulerServiceException {
        long interval = TimeUnit.DAYS.toMillis(1);
        long firstRun = TimeUnit.MINUTES.toMillis(30);
        GitAnalyticsJobRunner jobRunner = new GitAnalyticsJobRunner();
        schedulerService.registerJobRunner(INFORMATION_ANALYTICS_JOB_RUNNER_KEY, jobRunner);
        schedulerService.scheduleJob(
                INFORMATION_ANALYTICS_JOB_ID,
                JobConfig.forJobRunnerKey(INFORMATION_ANALYTICS_JOB_RUNNER_KEY)
                        .withRunMode(RunMode.RUN_LOCALLY)
                        .withSchedule(Schedule.forInterval(interval, new Date(System.currentTimeMillis() + firstRun))));
    }

    private void unscheduleJob() {
        schedulerService.unscheduleJob(INFORMATION_ANALYTICS_JOB_ID);
        schedulerService.unregisterJobRunner(INFORMATION_ANALYTICS_JOB_RUNNER_KEY);
    }

    private void publishAnalyticsEvent() {
        eventPublisher.publish(new GitAttributesAnalyticsEvent(this, config.getVersion().toString()));
    }

    private class GitAnalyticsJobRunner implements JobRunner {

        @Override
        public JobRunnerResponse runJob(JobRunnerRequest jobRunnerRequest) {
            publishAnalyticsEvent();
            return JobRunnerResponse.success();
        }
    }
}

