package com.sifang.modules.taskdispatch.util;

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

public class TimeSpan {

    private final Date start;
    private final Date end;

    /**
     * @param baseDate based date
     * @param span     must be of the format HH1:mm1-HH2:mm2
     */
    public TimeSpan(Date baseDate, String span) {
        Calendar d1 = Calendar.getInstance();
        d1.setTime(baseDate);
        String[] splits = span.split("-");
        String[] hm1 = splits[0].split(":");
        d1.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hm1[0]));
        d1.set(Calendar.MINUTE, Integer.parseInt(hm1[1]));
        this.start = d1.getTime();

        Calendar d2 = Calendar.getInstance();
        d2.setTime(baseDate);
        String[] hm2 = splits[1].split(":");
        d2.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hm2[0]));
        d2.set(Calendar.MINUTE, Integer.parseInt(hm2[1]));
        this.end = d2.getTime();
    }

    public TimeSpan(Date d1, Date d2) {
        this.start = d1;
        this.end = d2;
        assert d1.getTime() <= d2.getTime();
    }

    public static TimeDurationInfo getOverlapDurationInfo(long overlapDuration) {
        long hours = TimeUnit.MILLISECONDS.toHours(overlapDuration);
        long minutes = TimeUnit.MILLISECONDS.toMinutes(overlapDuration) % 60;
        long seconds = TimeUnit.MILLISECONDS.toSeconds(overlapDuration) % 60;
        return new TimeDurationInfo((int) hours, (int) minutes, (int) seconds);
    }

    public long getOverlapDuration(Date start1, Date end1, Date start2, Date end2) {
        // Find the latest start time
        long latestStart = Math.max(start1.getTime(), start2.getTime());
        // Find the earliest end time
        long earliestEnd = Math.min(end1.getTime(), end2.getTime());
        // Calculate the overlap duration in milliseconds
        if (latestStart <= earliestEnd) {
            return earliestEnd - latestStart;
        }
        return 0;
    }

    public long getOverlapDuration(TimeSpan span2) {
        return getOverlapDuration(this.getStart(), this.getEnd(), span2.getStart(), span2.getEnd());
    }

    public Date getStart() {
        return start;
    }

    public Date getEnd() {
        return end;
    }
}
