'use strict';

import * as sol from "../../solight/sol.js";

import * as serv from "../services/service.js";

const html = htm.bind(preact.h);


const schedule_persons = (persons) =>
    html`${persons.map(p => sol.personName(p)).join(', ')}`;

const schedule_time = (event) =>
    html`${sol.eventStartDate(event).toFormat('HH:mm')} – ${sol.eventEndDate(event).toFormat('HH:mm')}`;

const person_count_class = (count) => {
    switch (true) {
    case count === 1: return 'speaker-cnt-1';
    case count === 2: return 'speaker-cnt-2';
    case count === 3: return 'speaker-cnt-3';
    default: return 'speaker-cnt-many';
    }
};

const schedule_event = (event) => {
    const dnrString = sol.eventDoNotRecord(event) ? '✘' : '✔';
    const dnrClass = sol.eventDoNotRecord(event) ? 'dnr-true' : 'dnr-false';
    const speakerCnt = sol.eventPersonCount(event);
    const speakerCntClass = person_count_class(speakerCnt);
    return html`
    <tr>
      <td>${sol.eventTitle(event).slice(0, 30)}</td>
      <td>${schedule_persons(sol.eventPersons(event))}</td>
      <td class="${speakerCntClass}">${speakerCnt}</td>
      <td>${sol.eventType(event)}</td>
      <td>${schedule_time(event)}</td>
      <td class="${dnrClass}">${dnrString}</td>
    </tr>`;
};

const schedule_room = (events, room) => {
    const rn = sol.roomName(room);
    const evs = sol.eventsByRoomName(events, rn);
    const evss = sol.sortEventsByStartDate(evs);

    return html`
    <h3>Room: ${rn}</h3>
    <table>
      <tr>
        <th>Title</th>
        <th>Speakers</th>
        <th>#Speakers</th>
        <th>Type</th>
        <th>Time</th>
        <th>Record?</th>
      </tr>
      ${evss.map(e => schedule_event(e))}
    </table>`;
};

const schedule_day = (con, events, rooms, day) => {
    const dt = sol.dayStartDate(day);
    const di = sol.dayIndex(day);

    const evs = sol.eventsByDayIndex(events, di);
    const rms = sol.roomsByDayIndex(con, rooms, di);

    return html`
    <h2>Day ${di}: ${dt.setLocale('de-DE').toFormat('EEEE')}</h2>
    ${rms.map(r => schedule_room(evs, r))}`;
};

const schedule_table = (schedule) => {
    const con = sol.conference(schedule);

    const days = sol.allDays(schedule);
    const events = sol.allEvents(schedule);
    const rooms = sol.allRooms(schedule);

    return html`
    <h1>Schedule (v ${sol.scheduleVersion(schedule)})</h1>
    ${days.map(d => schedule_day(con, events, rooms, d))}`;
};


const update_main_slide = (data, time) => {
    console.log("Our data:");
    console.log(data);

    if (sol.defined(data.scheduleData)) {
        const schedule = data.scheduleData;

        const inner = html`
        ${schedule_table(schedule)}`;

        // Add main slide to info beamer
        const anchorElId = "main";
        const el = document.getElementById(anchorElId);
        preact.render(inner, el);
    };
};


export {
    update_main_slide
};
