const Course = require('../models/Course') ;

module.exports.addSchedule = async (req , res , next) => {
    try
    {
        //we will take startTime , endTime and link as input
        const startTime = req.body.startTime ;
        const endTime = req.body.endTime ;
        const link = req.body.link ;

        //we will alse take CourseId as input
        const parCourseId = req.body.parCourseId ;
        const course = await Course.findById(parCourseId) ;
        const meetings = [...course.meetings] ;
        let newMeet = {
            startTime : startTime ,
            endTime : endTime ,
            link : link
        } ;
        //pushing the new schedule
        meetings.push(newMeet) ;
        course.meetings = meetings ;
        await course.save() ;
        res.json({
            success : "added schedule"
        })
    }
    catch(err)
    {
        res.json({
            err : "Can not add"
        })
    }
}

module.exports.deleteSchedule = async (req , res , next) => {
    try{
        //we need index as input
        const index = req.body.index ;

        //we need courseId
        const parCourseId = req.body.parCourseId ;
        const course = await Course.findById(parCourseId) ;
        const meetings = [...course.meetings] ;
        if(index < (meetings.length))
        {
            meetings.splice(index , 1) ;
            course.meetings = meetings ;
            await course.save() ;
            res.json({
                success : "deleted schedule"
            })
        }
        else
        {
            res.json({
                err : "Index out of bound"
            })
        }
    }
    catch(err)
    {
        res.json({
            err : "Can not delete"
        })
    }
}

module.exports.editSchedule = async (req , res , next) => {
    try{
        //we will take startTime , endTime and link as input
        const startTime = req.body.startTime ;
        const endTime = req.body.endTime ;
        const link = req.body.link ;

        //we need to take the index as input
        const index = req.body.index ;

        //we will take courseId as input
        const parCourseId = req.body.parCourseId ;
        const course = await Course.findById(parCourseId) ;
        const meetings = [...course.meetings] ;
        if(index < (meetings.length))
        {
            let newMeet = {
                startTime : startTime ,
                endTime : endTime ,
                link : link
            } ;
            meetings[index] = newMeet ;
            course.meetings = meetings ;
            await course.save() ;
            res.json({
                success : "edited schedule"
            })
        }
        else
        {
            res.json({
                err : "Index out of bound"
            })
        }
    }
    catch(err)
    {
        res.json({
            err : "Can not edit"
        })
    }
}