//Calendar implementation for the HTWK Leipzig timetable. Evaluation and display of the individual dates in iCal format.
//Copyright (C) 2024 HTWKalender support@htwkalender.de

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Affero General Public License for more details.

//You should have received a copy of the GNU Affero General Public License
//along with this program.  If not, see <https://www.gnu.org/licenses/>.

import { Module } from "../model/module.ts";

export async function createIndividualFeed(modules: Module[]): Promise<string> {
  if (import.meta.env.SSR) {
    return "";
  }
  try {
    const response = await fetch("/api/feed", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(modules),
    });

    if (
      response.status === 429 ||
      response.status === 500 ||
      response.status != 200
    ) {
      return Promise.reject(response.statusText);
    }

    return await response.json();
  } catch (error) {
    // Catch possible errors and return an unfilled promise
    return Promise.reject(error);
  }
}

interface FeedResponse {
  modules: FeedModule[];
  collectionId: string;
  collectionName: string;
  id: string;
  retrieved: string;
  updated: string;
}

interface FeedModule {
  course: string;
  name: string;
  reminder: boolean;
  userDefinedName: string;
  uuid: string;
}

export async function saveIndividualFeed(
  token: string,
  modules: Module[],
): Promise<string> {
  if (import.meta.env.SSR) {
    return "";
  }
  await fetch("/api/collections/feeds/records/" + token, {
    method: "PATCH",
    headers: {
      "Content-Type": "application/json",
    },
    body: '{"modules":' + JSON.stringify(modules) + "}",
  })
    .then(async (response) => {
      // parse response.json to FeedResponse
      const feedResponse: FeedResponse = await response.json();
      return feedResponse;
    })
    .then((response: FeedResponse) => {
      token = response.id;
    });
  return token;
}

export async function deleteIndividualFeed(token: string): Promise<void> {
  if (import.meta.env.SSR) {
    return;
  }
  await fetch("/api/feed?token=" + token, {
    method: "DELETE",
  })
    .then((response) => {
      if (response.ok) {
        return Promise.resolve(response);
      } else {
        return Promise.reject(response);
      }
    })
    .catch((error) => {
      return Promise.reject(error);
    });
}
