import Graph from 'graphology';
import { LogInStatusUpdateEscapeTool } from './AuthProvider.jsx';

// This is wrapper functtions to do requests to the api, from the frontend.

export const apiUrl = `${window.location.origin}/api`;


//lil helper to throw errorrs from the promise when we get not-ok results
export const shoofetch = (url, config) => fetch(url, {...defaults, ...config})
    .then(async (res) => {
      if (res.status == 401) {
        LogInStatusUpdateEscapeTool.setLoggedIn(false);
      }
      
      localStorage.setItem("session", res.session);

      if (!res.ok) {
        throw new Error(`got an error from the server: ${await res.text()}`);
      }
      return res.json();
  });

const defaults = {
	headers: {'Content-Type': 'application/json'},
  credentials: 'include'
};

export async function postNewPage() {
	return shoofetch(`${apiUrl}/page/new`, {method: 'POST'})
}

export async function fetchPageList() {
	return shoofetch(`${apiUrl}/pages`, {method: 'GET'});
}

export async function fetchPage(number) {
	return shoofetch(`${apiUrl}/page/${number}`, {method: 'GET'});
}

export async function fetchPageHistory(number) {
  return shoofetch(`${apiUrl}/page/${number}/history`, {method: 'GET'});
}

export async function fetchPageAtEdit(number, id) {
  return shoofetch(`${apiUrl}/page/${number}/${id}`, {method: 'GET'});
}

export async function postPage({id, title, description}) {
	return shoofetch(`${apiUrl}/page/${id}`, {
        method: 'POST',
        body: JSON.stringify({id: id, title: title, description: description}),
    })
}

export async function deletePage(id) {
	return shoofetch(`${apiUrl}/page/${id}`, {method: 'DELETE'});
}

export async function fetchGraph() {
  return shoofetch(`${apiUrl}/graph`, {method: 'GET'})
      .then((serialized) => {
        const graph = new Graph();
        graph.import(serialized);
        return graph;
    });
}

export async function createAccount({name, password, nonce}) {
  return shoofetch(`${apiUrl}/register`, {
    method: 'POST',
    body: JSON.stringify({name: name, password: password, nonce: nonce})
  })
}

export async function postLogIn({name, password}) {
  return shoofetch(`${apiUrl}/login`, { 
    method: 'POST', 
    body: JSON.stringify({name: name, password: password}) 
  }).then((res) => {
    LogInStatusUpdateEscapeTool.setLoggedIn(true);
    return res;
  })
}

export async function postLogOut() {
  return shoofetch(`${apiUrl}/logout`, { 
    method: 'POST' 
  }).then((res) => {
    LogInStatusUpdateEscapeTool.setLoggedIn(false);
    return res;
  })
}

export async function fetchProfile() {
  return shoofetch(`${apiUrl}/user`, {method: 'GET'});
}