package ru.yandex.qe.dispenser.quartz.trigger;

import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SimpleTrigger;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdScheduler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ru.yandex.qe.dispenser.quartz.job.QuartzTrackerCommentJob;

import static org.quartz.JobBuilder.newJob;
import static org.quartz.SimpleScheduleBuilder.simpleSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

public class QuartzTrackerCommentTrigger implements SingleTrigger, QuartzTrackerComment {

    public static final String TRIGGER_GROUP = "TrackerCommentGroupTrigger";
    public static final String JOB_GROUP = "TrackerCommentGroupJob";

    private static final Logger LOG = LoggerFactory.getLogger(QuartzTrackerCommentTrigger.class);

    private final Scheduler scheduler;

    public QuartzTrackerCommentTrigger(final StdScheduler scheduler) {
        this.scheduler = scheduler;
    }

    @Override
    public String getJobGroup() {
        return JOB_GROUP;
    }

    @Override
    public String getTriggerGroup() {
        return TRIGGER_GROUP;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean run(@NotNull final String issueKey, @NotNull final String comment, final @NotNull String summoned) {
        return doRun(issueKey, comment, summoned);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean run(@NotNull final String issueKey, @NotNull final String comment) {
        return doRun(issueKey, comment, null);
    }

    private boolean doRun(final @NotNull String issueKey, final @NotNull String comment, final @Nullable String summoned) {
        final String name = UUID.randomUUID().toString();

        final JobDetail job = newJob(QuartzTrackerCommentJob.class)
                .withIdentity(name, JOB_GROUP)
                .requestRecovery(true)
                .build();

        TriggerBuilder<SimpleTrigger> triggerBuilder = newTrigger()
                .withIdentity(name, TRIGGER_GROUP)
                .withSchedule(simpleSchedule()
                        .withRepeatCount(4)
                        .withIntervalInMinutes(15)
                        .withMisfireHandlingInstructionNextWithExistingCount())
                .startNow()
                .usingJobData("issueKey", issueKey)
                .usingJobData("comment", comment);
        if (StringUtils.isNotEmpty(summoned)) {
            triggerBuilder = triggerBuilder.usingJobData("summoned", summoned);
        }
        final Trigger trigger = triggerBuilder.build();

        try {
            scheduler.scheduleJob(job, trigger);
        } catch (SchedulerException e) {
            LOG.error("Error with scheduling QuartzTrackerCommentTrigger", e);
            return false;
        }

        return true;
    }
}
