import {Component, computed, inject, OnInit, signal} from '@angular/core';
import {isActive, IsActiveMatchOptions, Router, RouterOutlet} from '@angular/router';
import {TuiSegmented} from '@taiga-ui/kit';
import {TUI_BREAKPOINT, TuiAppearance, TuiButton, TuiDialog, TuiGroup, TuiIcon, TuiLoader} from '@taiga-ui/core';
import {SessionManager} from '@chatenium/chatenium-sdk/services/sessionManager';
import {LoadStatus, ServiceManager} from '../service-manager';
import {IndexedDB} from '../storage/indexed-db';
import {DmList} from './dm-list/dm-list';
import {JsonPipe} from '@angular/common';
import {WebSocketHandler} from '@chatenium/chatenium-sdk/core/webSocketHandler';
import {TranslatePipe, TranslateService} from '@ngx-translate/core';
import {environment} from '../../environments/environment';
import {TuiTabBarComponent, TuiTabBarItem} from '@taiga-ui/addon-mobile';
import {NetworkList} from './network-list/network-list';
import {PictureList} from './picture-list/picture-list';

@Component({
  selector: 'app-chat',
  imports: [
    RouterOutlet,
    TuiSegmented,
    TuiIcon,
    TuiButton,
    TuiLoader,
    DmList,
    JsonPipe,
    TuiAppearance,
    TuiGroup,
    TuiDialog,
    TranslatePipe,
    TuiTabBarComponent,
    TuiTabBarItem,
    NetworkList,
    PictureList
  ],
  templateUrl: './chat.html',
  styleUrl: './chat.scss',
})
export class Chat implements OnInit {
  serviceManager = inject(ServiceManager)
  indexedDb = inject(IndexedDB)
  breakpoint = inject(TUI_BREAKPOINT)
  router = inject(Router)

  routerOutletActive = signal(false)

  navigationActiveIndex = 0
  // Mobile navigation //
  protected readonly tabBarItems = [
    {
      text: "chat.tabBar.tab1",
      icon: '@tui.message-circle',
      implemented: true,
    },
    {
      text: "chat.tabBar.tab2",
      icon: '@tui.network',
      implemented: true,
    },
    {
      text: "chat.tabBar.tab3",
      icon: '@tui.image',
      implemented: false,
    },
    {
      text: "chat.tabBar.tab4",
      icon: '@tui.cog',
      implemented: false,
    }
  ];

  changeLogOpen = signal(false)

  async ngOnInit() {
    if (this.router.url.startsWith("/chat/network")) {
      this.navigationActiveIndex = 1
    } else if (this.router.url.startsWith("/chat/picture")) {
      this.navigationActiveIndex = 2
    }

    this.indexedDb.openDatabase().then(async () => {
      const session = await this.serviceManager.sessionManager.loadPreferredSession()
      this.serviceManager.currentSession.set(session)
      await WebSocketHandler.getInstance().connect(session.userData.userid, session.token)
    })

    setTimeout(() => {
      const latestRead = localStorage.getItem("changeLogLastRead")
      if (latestRead != environment.version) {
        this.changeLogOpen.set(true)
      }
    }, 50)
  }

  protected readonly LoadStatus = LoadStatus;
  protected readonly localStorage = localStorage;
  protected readonly environment = environment;
}
