import Tooltip from "../Tooltip/Tooltip";
import UptimeBarTooltip from "./UptimeBarTooltip";
import { Green } from "../../../Types/BrandColors";
import OneUptimeDate from "../../../Types/Date";
import React, { useEffect, useState, } from "react";
const DayUptimeGraph = (props) => {
    const [days, setDays] = useState(0);
    useEffect(() => {
        setDays(OneUptimeDate.getNumberOfDaysBetweenDatesInclusive(props.startDate, props.endDate));
    }, [props.startDate, props.endDate]);
    const getIncidentsForDay = (startOfDay, endOfDay) => {
        if (!props.incidents || props.incidents.length === 0) {
            return [];
        }
        return props.incidents.filter((incident) => {
            return OneUptimeDate.isBetween(incident.declaredAt, startOfDay, endOfDay);
        });
    };
    const getUptimeBar = (dayNumber) => {
        let color = props.defaultBarColor || Green;
        const todaysDay = OneUptimeDate.getSomeDaysAfterDate(props.startDate, dayNumber);
        const startOfTheDay = OneUptimeDate.getStartOfDay(todaysDay);
        const endOfTheDay = OneUptimeDate.getEndOfDay(todaysDay);
        const todaysEvents = props.events.filter((event) => {
            let doesEventBelongsToToday = false;
            /// if the event starts or end today.
            if (OneUptimeDate.isBetween(event.startDate, startOfTheDay, endOfTheDay)) {
                doesEventBelongsToToday = true;
            }
            if (OneUptimeDate.isBetween(event.endDate, startOfTheDay, endOfTheDay)) {
                doesEventBelongsToToday = true;
            }
            // if the event is outside start or end day but overlaps the day completely.
            if (OneUptimeDate.isBetween(startOfTheDay, event.startDate, endOfTheDay) &&
                OneUptimeDate.isBetween(endOfTheDay, startOfTheDay, event.endDate)) {
                doesEventBelongsToToday = true;
            }
            return doesEventBelongsToToday;
        });
        const secondsOfEvent = {};
        const eventColors = {};
        let currentPriority = 1;
        const eventLabels = {};
        for (const event of todaysEvents) {
            const startDate = OneUptimeDate.getGreaterDate(event.startDate, startOfTheDay);
            const endDate = OneUptimeDate.getLesserDate(event.endDate, OneUptimeDate.getLesserDate(OneUptimeDate.getCurrentDate(), endOfTheDay));
            const seconds = OneUptimeDate.getSecondsBetweenDates(startDate, endDate);
            if (!secondsOfEvent[event.eventStatusId.toString()]) {
                secondsOfEvent[event.eventStatusId.toString()] = 0;
            }
            secondsOfEvent[event.eventStatusId.toString()] += seconds;
            eventLabels[event.eventStatusId.toString()] = event.label;
            eventColors[event.eventStatusId.toString()] = event.color;
            // set bar color.
            if (currentPriority <= event.priority) {
                currentPriority = event.priority;
                // if there are no rules then use the color of the event.
                if (!props.barColorRules || props.barColorRules.length === 0) {
                    color = event.color;
                }
            }
        }
        let hasEvents = false;
        let totalDowntimeInSeconds = 0;
        let totalUptimeInSeconds = 0;
        const downtimeStatusIds = (props.downtimeEventStatusIds || []).map((id) => {
            return id.toString();
        });
        for (const key in secondsOfEvent) {
            hasEvents = true;
            const eventStatusId = key;
            const isDowntimeEvent = downtimeStatusIds.includes(eventStatusId);
            if (isDowntimeEvent) {
                const secondsOfDowntime = secondsOfEvent[key] || 0;
                totalDowntimeInSeconds += secondsOfDowntime;
            }
            else {
                totalUptimeInSeconds += secondsOfEvent[key] || 0;
            }
        }
        // now check bar rules and finalize the color of the bar
        const uptimePercentForTheDay = totalUptimeInSeconds + totalDowntimeInSeconds > 0
            ? (totalUptimeInSeconds /
                (totalDowntimeInSeconds + totalUptimeInSeconds)) *
                100
            : 100;
        for (const rules of props.barColorRules || []) {
            if (uptimePercentForTheDay >= rules.uptimePercentGreaterThanOrEqualTo) {
                color = rules.barColor;
                break;
            }
        }
        if (todaysEvents.length === 1 && !hasEvents) {
            hasEvents = true;
        }
        if (todaysEvents.length === 1) {
            hasEvents = true;
        }
        if (todaysEvents.length === 0) {
            hasEvents = false;
            color = props.defaultBarColor || Green;
        }
        // Get incidents for this day
        const dayIncidents = getIncidentsForDay(startOfTheDay, endOfTheDay);
        let className = "h-20 w-20";
        if (props.height) {
            className = "w-20 h-" + props.height;
        }
        // Build status durations for tooltip
        const statusDurations = [];
        for (const key in secondsOfEvent) {
            statusDurations.push({
                label: eventLabels[key] || "Unknown",
                seconds: secondsOfEvent[key] || 0,
                color: eventColors[key] || props.defaultBarColor || Green,
                isDowntime: downtimeStatusIds.includes(key),
            });
        }
        const hasDayIncidents = dayIncidents.length > 0;
        const isClickable = hasDayIncidents && Boolean(props.onBarClick);
        return (React.createElement(Tooltip, { key: dayNumber, richContent: React.createElement(UptimeBarTooltip, { date: todaysDay, uptimePercent: uptimePercentForTheDay, hasEvents: hasEvents, statusDurations: statusDurations, incidents: dayIncidents, onIncidentClick: props.onIncidentClick }) },
            React.createElement("div", { className: `${className}${isClickable ? " cursor-pointer hover:opacity-80" : ""}`, style: {
                    backgroundColor: color.toString(),
                }, onClick: isClickable
                    ? () => {
                        props.onBarClick(todaysDay, dayIncidents);
                    }
                    : undefined })));
    };
    const getUptimeGraph = () => {
        const elements = [];
        for (let i = 0; i < days; i++) {
            elements.push(getUptimeBar(i));
        }
        return elements;
    };
    return (React.createElement("div", { className: "flex space-x-0.5 rounded overflow-hidden" }, getUptimeGraph()));
};
export default DayUptimeGraph;
//# sourceMappingURL=DayUptimeGraph.js.map