import { env } from "$env/dynamic/private";
import { google } from 'googleapis';
const { GOOGLE_SHEET_ID, GOOGLE_APPLICATION_CREDENTIALS } = env;

const auth = GOOGLE_APPLICATION_CREDENTIALS && new google.auth.GoogleAuth({
  keyFile: GOOGLE_APPLICATION_CREDENTIALS, //the key file
  //url to spreadsheets API
  scopes: 'https://www.googleapis.com/auth/spreadsheets'
});


const googleApi = (async () => {

  if (!auth) return;

  const authClientObject = await auth.getClient();

  const googleSheetsInstance = google.sheets({ version: 'v4', auth: authClientObject });

  return googleSheetsInstance;
})();

async function getSheet() {
  return await (
    await googleApi
  ).spreadsheets.values.get({
    auth, //auth object
    spreadsheetId: GOOGLE_SHEET_ID, // spreadsheet id
    range: 'Gäste' //range of cells to read from.
  });
}

function parseBoolean(o, key: string) {
  if (key in o) {
    o[key] = o[key].length ? !!parseInt(o[key]) : o[key];
  }
}

function parseNumber(o, key: string) {
  if (key in o) {
    o[key] = o[key].length ? parseInt(o[key]) : null;
  }
}

async function _getData(): Promise<{ Name: string; Alter: number }[]> {
  const raw = await getSheet();

  const _rows = raw.data.values;

  if (!_rows) return [];

  const [headers, ...rows] = _rows;

  function parseRow(row: string[]) {
    const o: {
      schlafen?: boolean;
      frauen?: boolean;
      single?: boolean;
      männer?: boolean;
      veggies?: boolean;
      Name: string;
      Alter: number;
    } = {
      Name: '',
      Alter: 0
    };

    row.forEach((v, i) => {
      o[headers[i]] = v;
    });

    parseBoolean(o, 'Schlafen');
    parseBoolean(o, 'Frauen');
    parseBoolean(o, 'Single');
    parseBoolean(o, 'Männer');
    parseBoolean(o, 'Veggies');

    parseNumber(o, 'Alter');

    return o;
  }

  return rows.map((r: string[]) => parseRow(r));
}

let lastGetUpdate: number;
let cacheData: { Name: string; Alter: number }[];
export async function getData() {
  if (!lastGetUpdate || Date.now() - 10000 > lastGetUpdate) {
    cacheData = await _getData();
    lastGetUpdate = Date.now();
  }

  return cacheData;
}

export async function addPerson({ name, confidence, noble_name }: { name: string, confidence: number, noble_name: string }): Promise<unknown> {

  const api = await googleApi;

  if (!api) return;

  return api.spreadsheets.values.append({
    auth, //auth object
    spreadsheetId: GOOGLE_SHEET_ID, // spreadsheet id
    range: 'Gäste', //range of cells to read from.
    valueInputOption: 'RAW',
    resource: {
      values: [[name, `${Number(confidence).toFixed(2).replace(".", ",")}%`, '', '', '', '', '', '', '', noble_name]]
    }
  });
}
