import { Sprintf } from "../global/Sprintf";
import { Routes } from "../routes/Routes";
import { ReencryptionDTO } from "../dto/ReencryptionDTO";
import { ChatMessageDTO } from "../dto/ChatMessageDTO";
import { JsonAPI } from "../../chat/singleton/JsonAPI";
import * as log from "loglevel";
import { StatsDTO } from "../dto/StatsDTO";
import { createApiHeaders } from "./util";

export async function getAllMessages(user: string, authToken: string) {
  let response = await fetch(`${Routes.Admin.getAllMessages}${user}`, {
    method: "GET",
    headers: createApiHeaders(authToken),
  });
  return response.json() as Promise<ReencryptionDTO[]>;
}

async function getAllRegularUsers(authToken: string) {
  let response = await fetch(`${Routes.Admin.getOtherUsers}`, {
    method: "GET",
    headers: createApiHeaders(authToken),
  });
  let data = (await response.json()) as string[];
  return data;
}

export async function sendReencryptedMessages(
  rencryptionDTOs: ReencryptionDTO[],
  authToken: string
) {
  let headers = new Headers();
  //	console.log("Token = " + btoa("hmm" + ":" + "hmm"))

  // headers.append('Accept','application/json')
  headers.append("Content-Type", "application/json");
  headers.append("X-AUTH-TOKEN", authToken);
  fetch(Routes.Admin.reencrypt, {
    method: "POST",
    headers: headers,
    body: JSON.stringify(rencryptionDTOs),
  }).then((response) => console.log(response));
}

export async function getOneMessage(
  toUser: string,
  page: number,
  authToken: string
): Promise<ChatMessageDTO[]> {
  const url = Sprintf(JsonAPI.CHAT_MESSAGE_PAGE_GET, toUser, page, 1);
  log.debug(url);
  const response = await fetch(url, {
    method: "GET",
    headers: createApiHeaders(authToken),
  });
  log.debug(response.clone());
  // if (fetchErrorHandler(response.clone(), this._notificationService)) {
  //   return null;
  // }
  const data: Promise<any> = await response.json();
  function func(data: any) {
    const d1 = data.map((d: any) => {
      if (d.messageTime == null) return null;

      d.messageTime = new Date(d.messageTime);
      return d;
    });
    return d1;
  }
  const data2 = func(data);
  return data2;
}

export async function getStats(authToken: string) {
  const response = await fetch("/api/stats/", {
    headers: createApiHeaders(authToken),
    method: "GET",
  });
  return (await response.json()) as StatsDTO;
}
