import { Time, DateTime } from '@silane/datetime';


/**
 * @param {import('../sharedworker/datastores/data-importer-exporter').ExportedData} data
 */
export function toJSONObject(data) {
  return {
    timeLabels: data.timeLabels.map(x => ({
      ...x,
      startTime: x.startTime.isoFormat(), endTime: x.endTime.isoFormat(),
    })),
    studentGrades: data.studentGrades.map(x => ({ ...x })),
    resources: data.resources.map(x => ({ ...x })),
    resourceHours: data.resourceHours.map(x => ({
      ...x,
      startTime: x.startTime.isoFormat(), endTime: x.endTime.isoFormat(),
    })),
    events: data.events.map(x => ({
      ...x, startTime: x.startTime.isoFormat(), endTime: x.endTime.isoFormat(),
    })),
    eventChanges: data.eventChanges.map(x => ({ ...x })),
  };
}

/**
 * @param {ReturnType<typeof toJSONObject>} jsonObject
 * @returns {import('../sharedworker/datastores/data-importer-exporter').ExportedData}
 */
export function fromJSONObject(jsonObject) {
  return {
    timeLabels: jsonObject.timeLabels.map(x => ({
      id: x.id, label: x.label, disabled: x.disabled,
      startTime: Time.fromISOFormat(x.startTime),
      endTime: Time.fromISOFormat(x.endTime),
    })),
    studentGrades: jsonObject.studentGrades.map(x => ({
      id: x.id, label: x.label,
    })),
    resources: jsonObject.resources.map(x => ({
      id: x.id, multiplicity: x.multiplicity, disabled: x.disabled,
      type: x.type, ...({
        classroom: { label: x.label },
        teacher: {
          firstName: x.firstName, lastName: x.lastName,
          firstNameKana: x.firstNameKana, lastNameKana: x.lastNameKana,
        },
        student: {
          firstName: x.firstName, lastName: x.lastName, grade: x.grade,
          firstNameKana: x.firstNameKana, lastNameKana: x.lastNameKana,
        },
      }[x.type]),
    })),
    resourceHours: jsonObject.resourceHours.map(x => ({
      id: x.id, resource: x.resource,
      startTime: DateTime.fromISOFormat(x.startTime),
      endTime: DateTime.fromISOFormat(x.endTime),
    })),
    events: jsonObject.events.map(x => ({
      id: x.id, resources: x.resources,
      startTime: DateTime.fromISOFormat(x.startTime),
      endTime: DateTime.fromISOFormat(x.endTime),
      timeLabel: x.timeLabel, memo: x.memo, color: x.color, type: x.type,
      ...({
        standard: {}, lesson: { subject: x.subject, frame: x.frame },
      }[x.type]),
    })),
    eventChanges: jsonObject.eventChanges.map(x => ({
      fromEvent: x.fromEvent, toEvent: x.toEvent,
      causeResources: x.causeResources,
    })),
  };
}
