<template>
  <nav>
    <ul>
      <li v-for="(item, key) in menu" :key="key" class="mainmenuitem"
        @click="openPage(item.path ?? null, !!item.children)">
        <span v-if="item.icon" :style="`background-image:url('/images/icons/${item.icon}')`"
          class="menu-icon">&nbsp;</span>
        <span>{{ $t(`navigation.${key}`) }}</span>
        <ul v-if="item.children" class="submenu1">
          <li v-for="(subitem, subkey) in item.children" :key="subitem.text"
            @click="openPage(subitem.path ?? null, !!subitem.children && subkey !== 'forum')">
            <span v-if="subitem.icon" :style="`background-image:url('/images/icons/${subitem.icon}')`"
              class="submenu-icon">&nbsp;</span>
            <span>{{ $t(`navigation.m-${key}.${subkey}`) }}</span>
            <span v-if="subkey === 'forum'" class="subsubmenu">&#x25B6;</span>
            <ul v-if="subkey === 'forum' && forumList.length > 0" class="submenu2">
              <li v-for="forum in forumList" :key="forum.id" @click="openForum(forum.id, $event)">
                {{ forum.name }}
              </li>
            </ul>
          </li>
          <li v-if="item.showLoggedinFriends === 1 && friendsList.length > 0" v-for="friend in friendsList" :key="friend.id">
            {{ friend.username }}
            <ul class="submenu2">
              <li @click="openChat(friend.id)">{{ $t('navigation.m-friends.chat') }}</li>
              <li @click="openProfile(friend.id)">{{ $t('navigation.m-friends.profile') }}</li>
            </ul>
          </li>
        </ul>
        <ul class="submenu1">
        </ul>
      </li>
    </ul>
    <div class="right-block">
      <span @click="accessMailbox" class="mailbox"></span>
      <span class="logoutblock">
        <span class="username">{{ user.username }} </span>
        <span @click="logout" class="menuitem">{{ $t('navigation.logout') }}</span>
      </span>
    </div>
  </nav>
</template>

<script>
import { mapGetters, mapActions } from 'vuex';
import apiClient from '@/utils/axios.js';

export default {
  name: 'AppNavigation',
  data() {
    return {
      forumList: [],
      friendsList: [],
    }
  },
  computed: {
    ...mapGetters(['menu', 'user', 'menuNeedsUpdate', 'socket']),
  },
  watch: {
    menuNeedsUpdate(newValue) {
      if (newValue) {
        this.loadMenu();
      }
    },
    socket(newValue) {
      if (newValue) {
        newValue.on('forumschanged', (data) => {
          this.fetchForums();
        });
        newValue.on('friendloginchanged', () => {
          this.fetchFriends();
        });
      }
    }
  },
  created() {
    if (this.user && this.user.id) {
      this.loadMenu();
      this.fetchForums();
      this.fetchFriends();
    } else {
      console.log(this.user);
    }
  },
  mounted() {
    if (this.$store.getters.socket) {
      console.log('connect sockets in navigation')
      this.$store.getters.socket.on('forumschanged', (data) => {
        this.fetchForums();
      });
      this.$store.getters.socket.on('friendloginchanged', () => {
        console.log('update friends');
        this.fetchFriends();
      });
    }
  },
  beforeUnmount() {
    if (this.$store.getters.socket) {
      this.$store.getters.socket.off('forumschanged');
      this.$store.getters.socket.off('friendloginchanged');
    }
  },
  methods: {
    ...mapActions(['loadMenu', 'logout']),
    openPage(url, hasSubmenu = false) {
      if (hasSubmenu) {
        return;
      }
      if (url) {
        this.$router.push(url);
      }
    },
    openForum(forumId, event) {
      event.stopPropagation();
      console.log('openForum', forumId);
      this.$router.push({ name: 'Forum', params: { id: forumId } });
    },

    async fetchForums() {
      try {
        const response = await apiClient.get('/api/forum');
        this.forumList = response.data;
      } catch (error) {
        console.error('Error fetching forums:', error);
      }
    },

    async fetchFriends() {
      try {
        const response = await apiClient.get('/api/socialnetwork/friends/loggedin');
        this.friendsList = response.data;
      } catch (error) {
        console.error('Error fetching friends:', error);
      }
    },

    async openProfile(hashedId) {
      console.log(hashedId);
      this.$root.$refs.userProfileDialog.userId = hashedId;
      this.$root.$refs.userProfileDialog.open();
    },

    async openChat(hashedId) { 
      try {
        
      } catch (error) {
        
      }
    }
  }
};
</script>

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

nav,
nav>ul {
  display: flex;
  justify-content: space-between;
  background-color: #F9A22C;
  color: #000000;
  padding: 0;
  flex-direction: row;
  margin: 0;
  cursor: pointer;
  z-index: 999;
}

ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

nav>ul>li {
  padding: 0 1em;
  line-height: 2.5em;
  transition: background-color 0.25s;
}

nav>ul>li:hover {
  background-color: #D37C06;
  white-space: nowrap;
}

nav>ul>li:hover>span {
  color: #000000;
}

nav>ul>li:hover>ul {
  display: inline-block;
}

a {
  text-decoration: none;
}

.right-block {
  display: flex;
  gap: 10px;
}

.logoutblock {
  display: flex;
  flex-direction: column;
}

.menuitem {
  cursor: pointer;
  color: #7E471B;
}

.mailbox {
  background-image: url('@/assets/images/icons/message24.png');
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  padding-left: 24px;
  text-align: left;
}

.mainmenuitem {
  position: relative;
}

.submenu1 {
  position: absolute;
  border: 1px solid #7E471B;
  background-color: #F9A22C;
  left: 0;
  top: 2.5em;
  max-height: 0;
  overflow: visible;
  opacity: 0;
  visibility: hidden;
  transition: max-height 0.25s ease-in-out, opacity 0.05s ease-in-out, visibility 0s 0.05s;
}

.mainmenuitem:hover .submenu1 {
  max-height: 500px;
  opacity: 1;
  visibility: visible;
  transition: max-height 0.25s ease-in-out, opacity 0.05s ease-in-out, visibility 0s;
}

.submenu1>li {
  padding: 0.5em;
  line-height: 1em;
  color: #7E471B;
  position: relative;
}

.submenu1>li:hover {
  color: #000000;
  background-color: #D37C06;
}

.menu-icon {
  width: 24px;
  height: 24px;
  margin-right: 3px;
  background-repeat: no-repeat;
  display: inline-block;
  line-height: 1.6em;
}

.submenu-icon {
  width: 1.2em;
  height: 1em;
  margin-right: 3px;
  background-repeat: no-repeat;
  display: inline-block;
  line-height: 1em;
  background-size: 1.2em 1.2em;
}

.submenu2 {
  position: absolute;
  background-color: #F9A22C;
  left: 100%;
  top: 0;
  border: 1px solid #7E471B;
  max-height: 0;
  overflow: hidden;
  opacity: 0;
  visibility: hidden;
  transition: max-height 0.25s ease-in-out, opacity 0.05s ease-in-out, visibility 0s 0.05s;
}

.submenu1>li:hover .submenu2 {
  max-height: 500px;
  opacity: 1;
  visibility: visible;
  transition: max-height 0.25s ease-in-out, opacity 0.05s ease-in-out, visibility 0s;
}

.submenu2>li {
  padding: 0.5em;
  line-height: 1em;
  color: #7E471B;
}

.submenu2>li:hover {
  color: #000000;
  background-color: #D37C06;
}

.subsubmenu {
  float: right;
  font-size: 8pt;
  margin-right: -4px;
}
</style>
