<script setup>
import axios from 'axios'
const dataStore = useDataStore()
const accounts = ref([])

//accounts.value = dataStore.emailAccounts.map(i => { return { label: i.emailAddress, emailEngingeId: i.emailEngineId }})

const mailboxes = ref({})
const messages = ref([])
const selectedMailbox = ref("INBOX")
const selectedAccount = ref(null)
const selectedMessage = ref(null)
const setup = async () => {
  accounts.value = dataStore.emailAccounts.map((i,index) => {
    let item = { label: i.emailAddress, emailEngineId: i.emailEngineId }
    if(index === 0) {
      item.defaultOpen = true
    }
    return item

  })

  for await (const account of accounts.value) {
    console.log(account.emailEngineId)
    const {data,error} = await axios.get(`http://157.90.231.142:3000/v1/account/${account.emailEngineId}/mailboxes`, {headers: { 'Authorization': 'Bearer dadb572465fba648590f31557f68028a750b47b278d87c1773e8fd09670eec59'}})
    console.log(data)
    console.log(error)
    mailboxes.value[account.emailEngineId] = data.mailboxes
  }
}



const selectMailbox = async (account, mailbox) => {
  selectedMailbox.value = mailbox
  const {data,error} = await axios.get(`http://157.90.231.142:3000/v1/account/${account}/messages?path=${ mailbox.path}`, {headers: { 'Authorization': 'Bearer dadb572465fba648590f31557f68028a750b47b278d87c1773e8fd09670eec59'}})
  console.log(data)
  console.log(error)
  messages.value = data.messages
  selectedAccount.value = account
}
const messageHTML = ref(null)
const messageText = ref(null)
const selectMessage = async (account, message) => {
  console.log(message)
  selectedMessage.value = message
  const {data,error} = await axios.get(`http://157.90.231.142:3000/v1/account/${account}/text/${message.text.id}`, {headers: { 'Authorization': 'Bearer dadb572465fba648590f31557f68028a750b47b278d87c1773e8fd09670eec59'}})
  messageHTML.value = data.html
  messageText.value = data.plain
}

const addFlags = async (account, message, flags) => {
  console.log(flags)
  const {data,error} = await axios({
    method: "PUT",
    url: `http://157.90.231.142:3000/v1/account/${account}/message/${message.id}`,
    headers: { 'Authorization': 'Bearer dadb572465fba648590f31557f68028a750b47b278d87c1773e8fd09670eec59'},
    data: {
      flags: {
        add: flags
      }
    }
  })

  console.log(data)
  console.log(error)
}

const removeFlags = async (account, message, flags) => {
  console.log(flags)
  const {data,error} = await axios({
    method: "PUT",
    url: `http://157.90.231.142:3000/v1/account/${account}/message/${message.id}`,
    headers: { 'Authorization': 'Bearer dadb572465fba648590f31557f68028a750b47b278d87c1773e8fd09670eec59'},
    data: {
      flags: {
        delete: flags
      }
    }
  })

  console.log(data)
  console.log(error)
}

const setSeen = async (seen,message) => {
  if(seen) {
    await addFlags(selectedAccount.value,message, ["\\Seen"])
    await selectMailbox(selectedAccount.value, selectedMailbox.value)
  } else {
    await removeFlags(selectedAccount.value,message, ["\\Seen"])
    await selectMailbox(selectedAccount.value, selectedMailbox.value)
  }
}

const moveTo = async (destinationPath) => {
  const {data,error} = await axios({
    method: "PUT",
    url: `http://157.90.231.142:3000/v1/account/${selectedAccount.value}/message/${selectedMessage.value.id}/move`,
    headers: { 'Authorization': 'Bearer dadb572465fba648590f31557f68028a750b47b278d87c1773e8fd09670eec59'},
    data: {
      path: destinationPath
    }
  })

  console.log(data)
  console.log(error)
  selectedMessage.value = null
  messageHTML.value = null
  messageText.value = null
  selectMailbox(selectedAccount.value, selectedMailbox.value)
}

const downloadAttachment = async (attachment) => {
  const {data,error} = await axios({
    method: "GET",
    url:   `http://157.90.231.142:3000/v1/account/${selectedAccount.value}/attachment/${attachment.id}`,
    headers: { 'Authorization': 'Bearer dadb572465fba648590f31557f68028a750b47b278d87c1773e8fd09670eec59'},
    responseType: "blob"
  })

  const downloadURL = URL.createObjectURL(new Blob([data]))
  const link = document.createElement('a')
  link.href = downloadURL
  link.setAttribute('download', attachment.filename)
  document.body.appendChild(link)
  link.click()
  link.remove()
    console.log(data)
    console.log(error)
}


setup()
</script>

<template>

  <div class="flex flex-row">
    <div id="mailboxlist">
      <UAccordion
        :items="accounts"
      >
        <template #default="{ item, index, open }">
          <UButton variant="soft" class="mt-3">

            <span class="truncate">{{ item.label }}</span>

            <template #trailing>
              <UIcon
                  name="i-heroicons-chevron-right-20-solid"
                  class="w-5 h-5 ms-auto transform transition-transform duration-200"
                  :class="[open && 'rotate-90']"
              />
            </template>
          </UButton>
        </template>
        <template #item="{ item }">
          <div
              v-for="mailbox in mailboxes[item.emailEngineId]"
              class="my-3"
          >
            <UButton
                @click="selectMailbox(item.emailEngineId, mailbox)"
                variant="outline"
            >
              <span v-if="mailbox.name === 'Trash'">Papierkorb</span>
              <span v-else-if="mailbox.name === 'INBOX'">Eingang</span>
              <span v-else-if="mailbox.name === 'Sent'">Gesendet</span>
              <span v-else-if="mailbox.name === 'Drafts'">Entwürfe</span>
              <span v-else-if="mailbox.name === 'spambucket'">Spam</span>
              <span v-else>{{mailbox.name}}</span>
              <UBadge v-if="mailbox.messages > 0">{{mailbox.messages}}</UBadge>
            </UButton>
          </div>


        </template>
      </UAccordion>

    </div>
    <UDivider orientation="vertical" class="maiLDivider"/>
    <div id="maillist">
      <div
          v-for="message in messages"
          v-if="messages.length > 0"
      >
        <div
            :class="message === selectedMessage ?  ['message','text-primary-500'] : ['message']"
            @click="selectMessage(selectedAccount, message),
                    !message.flags.includes('\\Seen') ? setSeen(true,message) : null"
        >
          <UChip
            position="top-left"
            :show="!message.flags.includes('\\Seen')"
          >
            <h1>{{message.from.name ||message.from.address}}</h1>
          </UChip>

          <h3>{{message.subject}}</h3>
        </div>
        <UDivider class="my-3"/>

      </div>
      <div
        v-else
      >
        Keine E-Mails in diesem Postfach
      </div>


    </div>
    <UDivider orientation="vertical" class="maiLDivider"/>

    <div id="mailcontent" v-if="selectedMessage">
      <Toolbar>
        <!--<UButton
            @click="setup"
        >Setup</UButton>
        <UButton>+ Neu</UButton>
        <UButton>Sync</UButton>
        <UButton>Papierkorb</UButton>
        <UButton>Weiterleiten</UButton>
        <UButton>Antworten</UButton>-->
        <UButton
          @click="setSeen(false,selectedMessage)"
        >
          Als Ungelesen markieren
        </UButton>
        <UButton
          @click="moveTo('INBOX.Trash')"
          icon="i-heroicons-trash"
        >

        </UButton>
      </Toolbar>
      <UAlert
        v-if="selectedMessage"
        :title="attachment.filename"
        v-for="attachment in selectedMessage.attachments"
        class="my-3"
        :actions="[{label: 'Download', click:() => {downloadAttachment(attachment)}}]"
      >

      </UAlert>
      <iframe
          v-if="messageHTML"
          style="width: 100%; height: 100%"
          :srcdoc="messageHTML">
      </iframe>
      <pre
          class="text-wrap"
          v-else-if="messageText">
        {{messageText}}
      </pre>
    </div>
  </div>

</template>

<style scoped>
.maiLDivider {
  width: 5vw;
}

#mailboxlist {
  width: 15vw;
  height: 95vh;
  overflow-y: scroll;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

#mailboxlist::-webkit-scrollbar {
  display: none;
}

#maillist {
  width: 25vw;
  height: 88vh;
  overflow-y:scroll;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

#maillist::-webkit-scrollbar {
  display: none;
}

#mailcontent {
  width: 55vw;
  height: 88vh;
  overflow-y:scroll;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}

#mailcontent::-webkit-scrollbar {
  display: none;
}

.message {
  //border: 1px solid  #69c350;
  margin-right: 1em;
  padding: 0.5em;
}


.message:hover {
  background-color: #69c350;
}

.message h1 {
  font-weight: bold;
}
</style>