package com.atlassian.stash.internal.scheduling;

import com.atlassian.bitbucket.validation.annotation.OptionalString;
import com.atlassian.scheduler.config.CronScheduleInfo;
import com.atlassian.scheduler.config.Schedule;

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

@DiscriminatorValue("0")    // matches Schedule.Type.CRON_EXPRESSION.ordinal()
@Entity
public class InternalClusteredCronJob extends InternalClusteredJob {

    @Column(name = "cron_expression")
    @OptionalString(size = 255)
    private final String cronExpression;

    @Column(name = "time_zone")
    private final TimeZone timeZone;

    @SuppressWarnings("unused") //Required for Hibernate
    protected InternalClusteredCronJob() {
        cronExpression = null;
        timeZone = null;
    }

    protected InternalClusteredCronJob(Builder builder) {
        super(builder);
        CronScheduleInfo cronScheduleInfo = builder.schedule.getCronScheduleInfo();
        cronExpression = cronScheduleInfo.getCronExpression();
        timeZone = cronScheduleInfo.getTimeZone();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o instanceof InternalClusteredCronJob) {
            InternalClusteredCronJob that = (InternalClusteredCronJob) o;
            return super.equals(that) &&
                    Objects.equals(cronExpression, that.cronExpression) &&
                    Objects.equals(timeZone, that.timeZone);
        }
        return false;
    }

    @Override
    @Nonnull
    public Schedule getSchedule() {
        return Schedule.forCronExpression(cronExpression, timeZone);
    }

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

}
