const fs = require('fs');

const CLASSROOM_TEMPLATE = `
// schedule = _schedule_, classroom = _classroom_
$classroom = ClassRoom::find(_classroom_);
$schedule = Schedule::find(_schedule_);
`.trim();

const TIME_TEMPLATE = `
$schedule->classrooms()->attach($classroom->id, ['date_epoch' => strtotime('_date_')]);
`.trim();

const parseDay = dateString => {
    const [day, month, year] = dateString.split('-');
    return new Date(year, month - 1, day);
};

function getAllDays(startDate, endDate) {
    var dateArray = [];

    startDate = parseDay(startDate);
    endDate = parseDay(endDate);

    var currentDate = startDate;

    while (currentDate <= new Date(endDate)) {
        dateArray.push(
            currentDate.getFullYear() + '-' + (currentDate.getMonth() + 1) + '-' + currentDate.getDate() );
        currentDate.setDate(currentDate.getDate() + 1);
    }

    return dateArray;
}

const classroom_activity_txt = fs.readFileSync('./classroom_activity.txt', { encoding: 'utf-8' });
const classroom_activity_list = classroom_activity_txt
    .trim()
    .split(/\n/g)
    .map(r => r.split(':').map(r => r.trim()));

const startDates = classroom_activity_list.map(e => e[0]);
const endDates = classroom_activity_list.map(e => e[1]);
const classrooms = classroom_activity_list.map(e => e[2]);

const temp = classroom_activity_list.map((c, idx) => {
    // // Example usage:
    var startDate = startDates[idx];
    var endDate = endDates[idx];
    var classroom = classrooms[idx];
    var schedule = idx + 1;

    var daysList = getAllDays(startDate, endDate);
    var dayString = daysList.map(d => TIME_TEMPLATE.replace('_date_', d)).join('\n');
    var before_dayString = CLASSROOM_TEMPLATE.replace(/_classroom_/g, classroom).replace(/_schedule_/g, schedule);

    return [before_dayString, dayString].join('\n');
});

fs.writeFileSync('./write_classroom_activity.out', temp.join('\n\n'), { encoding: 'utf-8' });
