<!--
 Copyright (C) 2020 - 2024 3NSoft Inc.

 This program is free software: you can redistribute it and/or modify it under
 the terms of the GNU General Public License as published by the Free Software
 Foundation, either version 3 of the License, or (at your option) any later
 version.

 This program is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 this program. If not, see <http://www.gnu.org/licenses/>.
-->
<script lang="ts" setup>
import { computed, onBeforeMount, onBeforeUnmount, ref } from 'vue';
import { storeToRefs } from 'pinia';
import { Ui3nMenu } from '@v1nt1248/3nclient-lib';
import { makeServiceCaller } from '../../shared-libs/ipc/ipc-service-caller';
import { AppVersion } from '@/constants';
import prLogo from '@/assets/images/privacysafe-logo.svg';
import { useAppStore } from '@/store/app.store';
import { useContactsStore } from '@/store/contacts.store';
import { UISettings } from '@/services/ui-settings';
import type { AppContactsService } from '@/types';
import ContactIcon from '@/components/contact-icon.vue';

const appStore = useAppStore();
const { user, connectivityStatus } = storeToRefs(appStore);
const { getAppConfig, getUser, getConnectivityStatus, setLang, setColorTheme } = appStore;

const contactsStore = useContactsStore();
const { getContactList } = contactsStore;

const connectivityStatusText = computed(() => connectivityStatus.value === 'online'
  ? 'app.status.connected.online'
  : 'app.status.connected.offline',
);
const connectivityTimerId = ref<ReturnType<typeof setInterval> | undefined>();

async function appExit() {
  w3n.closeSelf!();
}

onBeforeMount(async () => {
  try {
    await getUser();
    await getAppConfig();
    await getConnectivityStatus();

    await getContactList();

    connectivityTimerId.value = setInterval(getConnectivityStatus, 60000);

    const config = await UISettings.makeResourceReader();
    config.watchConfig({
      next: appConfig => {
        const { lang, colorTheme } = appConfig;
        setLang(lang);
        setColorTheme(colorTheme);
      },
    });

    const contactsSrvConnection = await w3n.rpc!.thisApp!('AppContactsInternal');
    const contactsSrv = makeServiceCaller(contactsSrvConnection, [], ['watchContactList']) as AppContactsService;
    contactsSrv.watchContactList({
      next: () => contactsStore.getContactList(),
      error: e => console.error(e),
      complete: () => contactsSrvConnection.close(),
    });
  } catch (e) {
    console.error('MOUNTED ERROR: ', e);
  }
});

onBeforeUnmount(() => {
  connectivityTimerId.value && clearInterval(connectivityTimerId.value);
});
</script>

<template>
  <div :class="$style.app">
    <div :class="$style.toolbar">
      <div :class="$style.toolbarTitle">
        <img
          :src="prLogo"
          alt="logo"
          :class="$style.toolbarLogo"
        />
        <div :class="$style.delimiter">/</div>
        <div :class="$style.info">
          Contacts
          <div :class="$style.version">v {{ AppVersion }}</div>
        </div>
      </div>

      <div :class="$style.user">
        <div :class="$style.userInfo">
          <span :class="$style.mail">
            {{ user }}
          </span>
          <span :class="$style.connection">
            {{ $tr('app.status') }}:
            <span :class="connectivityStatusText === 'app.status.connected.online' && $style.connectivity">
              {{ $tr(connectivityStatusText) }}
            </span>
          </span>
        </div>

        <ui3n-menu
          position-strategy="fixed"
          :offset-y="4"
        >
          <div :class="$style.icon">
            <contact-icon
              :name="user"
              :size="36"
              :readonly="true"
            />
          </div>

          <template #menu>
            <div :class="$style.menu">
              <div
                :class="$style.menuItem"
                @click="appExit"
              >
                {{ $tr('app.exit') }}
              </div>
            </div>
          </template>
        </ui3n-menu>
      </div>
    </div>

    <div :class="$style.content">
      <router-view v-slot="{ Component }">
        <transition>
          <component :is="Component" />
        </transition>
      </router-view>
    </div>
  </div>
</template>

<style lang="scss" module>
@import '../assets/styles/mixins';

.app {
  --main-toolbar-height: calc(var(--spacing-ml) * 3);

  position: fixed;
  inset: 0;
  background-size: cover;
}

.toolbar {
  position: relative;
  width: 100%;
  height: var(--main-toolbar-height);
  padding: 0 var(--spacing-m);
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--color-border-block-primary-default);
}

.toolbarTitle {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.toolbarLogo {
  position: relative;
  top: -2px;
  margin-right: var(--spacing-m);
}

.delimiter {
  font-size: 20px;
  font-weight: 500;
  color: var(--color-text-control-accent-default);
  margin-right: var(--spacing-m);
  padding-bottom: 2px;
}


.info {
  position: relative;
  width: max-content;
  font-size: var(--font-16);
  font-weight: 500;
  color: var(--color-text-control-primary-default);
  display: flex;
  justify-content: flex-start;
  align-items: center;
  gap: var(--spacing-s);
  padding-bottom: calc(var(--spacing-xs) / 2);
}

.version {
  font-size: var(--font-16);
  font-weight: 500;
  color: var(--color-text-control-secondary-default);
  line-height: var(--font-16);
}

.user {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.userInfo {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-end;
  margin-right: var(--spacing-m);

  span:not(.connectivity) {
    color: var(--color-text-control-primary-default);
    line-height: 1.4;
  }
}

.mail {
  font-size: var(--font-14);
  font-weight: 600;
}

.connection {
  font-size: var(--font-12);
  font-weight: 500;
}

.connectivity {
  color: var(--success-content-default);
}

.icon {
  position: relative;
  cursor: pointer;
}

.menu {
  position: relative;
  background-color: var(--color-bg-control-secondary-default);
  width: max-content;
  border-radius: var(--spacing-xs);
  @include elevation(1);
}

.menuItem {
  position: relative;
  width: 60px;
  height: var(--spacing-l);
  padding: 0 var(--spacing-s);
  font-size: var(--font-13);
  font-weight: 500;
  color: var(--color-text-control-primary-default);
  display: flex;
  justify-content: flex-start;
  align-items: center;
  cursor: pointer;

  &:hover {
    background-color: var(--color-bg-control-primary-hover);
    color: var(--color-text-control-accent-default);
  }
}

.content {
  position: fixed;
  left: 0;
  right: 0;
  top: calc(var(--main-toolbar-height) + 1px);
  bottom: 0;
}
</style>
