import { ref, reactive, watch, computed } from "vue";


function isIterable(obj) {
  // checks for null and undefined
  if (obj == null) {
    return false;
  }
  return typeof obj[Symbol.iterator] === 'function';
}

export async function homeAction(options = {}) {
  return await ( await fetch("/", {
    method: "POST",
    headers: {
      Accept: "application/json",
    },
    body: JSON.stringify(options),
  })).json();
}

export async function getQuery(query, options = {}) {
  return (await ( await fetch("/api/query", {
    method: "POST",
    headers: {
      Accept: "application/json",
      // completely unsafe
      // Authorization: "Basic "+btoa("api@api.de:H]RcScp];76!-PB")
    },
    body: JSON.stringify({
      query: query,
      ...options
    }),
  })).json()).result;
}


async function getKirby(endpoint) {
  return (await (await fetch("/api"+endpoint, {
    method: "GET",
    headers: {
      // completely unsafe
      Authorization: "Basic "+btoa("api@api.de:H]RcScp];76!-PB")
    }
  })).json()).data;
  // .catch(error => {
  //   console.log("Error:", error);
  // });
}

export async function setKirby(endpoint, data) {
  const response = await fetch(`/${endpoint}`, {
      method: "POST",
      cache: "no-cache",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        action: "update",
        data: data
      }),
  });
  const ret = await response.json();
  return ret;
}

function updateContent(endpoint, data) {
  return fetch("/api"+endpoint, {
    method: "PATCH",
    headers: {
      // "X-CSRF" : g_csrf,
      // completely unsafe
      "Authorization": "Basic "+btoa("api@api.de:H]RcScp];76!-PB")
    },
    body: JSON.stringify(data)
  })
  .then(response => response.json())
  .then(response => {
    // console.log(response.data);
  })
  .catch(error => {
    console.log("Error:", error);
  });
}


export const convertToPages = async (obj) => {
  for(var key in obj){
    if (obj[key].hasOwnProperty("link")) {
      obj[key] = await kirbyPage(obj[key].link);
    } else if (Array.isArray(obj[key]) || typeof obj[key] === 'object' ) {
      obj[key] = convertToPages(obj[key]);
    }
  }
  return obj;
}


export const kirbyPage = async (endpoint) => {
  if (!endpoint.startsWith("/pages/")){
    endpoint = "/pages/"+endpoint.replaceAll("/","+");
  }

  let patch = false;
  const page = new Proxy(reactive({}), {
      async set(target, key, value) {
          if(value.hasOwnProperty("uuid") && value.uuid.startsWith("page://")){
            value = await kirbyPage(value.link);
          }
          if (Array.isArray(value) || typeof value === 'object' ) {
            for(var i in value){
              if (value[i].hasOwnProperty("uuid") && value[i].uuid.startsWith("page://")) {
                value[i] = await kirbyPage(value[i].link);
              }
            }
          }
          target[key] = value;
          if (patch) {
            const data = {};
            if (value.isPage) {
              data[key] = "page://"+value.uuid;
            } else if (Array.isArray(value) || typeof value === 'object' ) {
              data[key] = [];
              for (var i in value) {
                if (value[i].isPage) {
                  data[key].push("page://"+value[i].uuid);
                } else {
                  data[key].push(value[i]);
                }
              }
            } else {
              data[key] = value;
            }
            updateContent(endpoint, data);
          }
          return true;
      },
      get(target, prop, receiver) {
        if (prop == "isPage") {
          return true;
        }
        return target[prop];
      }
    }
  );
  const lastData = ref({});
  const kData = await getKirby(endpoint);
  Object.assign(page, kData.content);

  patch = true;
  return page;
}
