<script lang="ts" setup>
import { inject, onMounted, Ref, ref } from "vue";
import { LoggerKey } from "../ts/class/Logger";

const logger = inject(LoggerKey);
const loading = ref(true);
const doFetch = () => fetch("https://www.torn.com/page.php", {
  "headers": {
    "accept": "*/*",
    "sec-ch-ua-mobile": "?0",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-origin",
    "x-requested-with": "XMLHttpRequest"
  },
  "referrer": "https://www.torn.com/page.php?sid=events",
  "referrerPolicy": "strict-origin-when-cross-origin",
  "body": (() => {
    const data = new FormData();
    data.append('sid', 'eventsData');
    return data;
  })(),
  "method": "POST",
  "mode": "cors",
  "credentials": "include"
});
const events: Ref<{ ID: string, message: string, time: number, isNew: boolean }[]> = ref([]);
const DateTimeFormatter = (ts: number) => {
  let date = new Date(ts);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};
const loadData = async () => {
  loading.value = true;
  events.value = [];
  let res;
  try {
    res = await (await doFetch()).json();
    if (res.success) {
      events.value = res.events;
      if (res['newEventsAmount']) {
        for (let i = 0; i < res['newEventsAmount']; i++) {
          events.value[i].isNew = true;
        }
      }
      loading.value = false;
    }
  } catch (e) {
    logger.error(e.stack);
  }
};

onMounted(loadData);
</script>

<template>
  <el-button @click="loadData">刷新</el-button>
  <el-divider/>
  <el-timeline v-if="!loading">
    <el-timeline-item v-for="ev in events" :color="ev.isNew?'#0bbd87':''"
                      :timestamp="DateTimeFormatter(ev.time*1000)">
      <span v-html="ev.message"></span>
    </el-timeline-item>
  </el-timeline>
  <el-skeleton v-if="loading" :rows="10" animated/>
</template>

<style scoped></style>