import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import KU from "./KUSchedule.js";
import scheduleApi from "../../apis/schedule.api";
import catchErrors from "../../utils/catchErrors.js";

const ScheduleCarousel = () => {
    const [scheduleList, setScheduleList] = useState([])
    const [error, setError] = useState("")
    const { date } = useParams()

    useEffect(() => {
        getSchedule(date)
        return () => {
            getSchedule(date)
        }
    }, [])

    useEffect(() => {
        getSchedule(date)
        return () => {
            getSchedule(date)
        }
    }, [date])

    async function getSchedule(date) {
        try {
            setError("")
            const resList = await scheduleApi.getbyDate(date)
            setScheduleList(resList)
        } catch (error) {
            catchErrors(error, setError)
        }
    }

    return (
        <div id="scheduleListCarousel" className="carousel slide" data-bs-ride="carousel">
            <div className="carousel-inner">
                {scheduleList.length !== 0 ?
                    scheduleList.map((schedule, idx) =>
                        <div className={"carousel-item" + (idx === 0 ? " active" : "")}>
                            <KU key={idx} schedule={schedule} />
                        </div>) : null}
            </div>
        </div>
    )
}

export default ScheduleCarousel