package com.atlassian.stash.internal.scheduling;

import com.atlassian.scheduler.config.IntervalScheduleInfo;
import com.atlassian.scheduler.config.Schedule;
import com.atlassian.stash.internal.util.TimestampUtils;

import javax.annotation.Nonnull;
import javax.persistence.*;
import java.util.Date;
import java.util.Objects;

@DiscriminatorValue("1")    // matches Schedule.Type.INTERVAL.ordinal()
@Entity
public class InternalClusteredIntervalJob extends InternalClusteredJob {

    @Column(name = "interval_millis")
    private final Long intervalMillis;

    @Column(name = "first_run")
    @Temporal(TemporalType.TIMESTAMP)
    private final Date firstRun;

    @SuppressWarnings("unused") //Required for Hibernate
    protected InternalClusteredIntervalJob() {
        intervalMillis = null;
        firstRun = null;
    }

    protected InternalClusteredIntervalJob(Builder builder) {
        super(builder);
        IntervalScheduleInfo intervalScheduleInfo = builder.schedule.getIntervalScheduleInfo();
        intervalMillis = intervalScheduleInfo.getIntervalInMillis();
        firstRun = intervalScheduleInfo.getFirstRunTime();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o instanceof InternalClusteredIntervalJob) {
            InternalClusteredIntervalJob that = (InternalClusteredIntervalJob) o;
            return super.equals(that) &&
                    Objects.equals(intervalMillis, that.intervalMillis) &&
                    TimestampUtils.equalToSecondPrecision(firstRun, that.firstRun);
        }
        return false;
    }

    @Override
    @Nonnull
    public Schedule getSchedule() {
        return Schedule.forInterval(intervalMillis, firstRun);
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

}
