import {Component, inject, input, OnInit} from '@angular/core';
import {ChatService} from '@chatenium/chatenium-sdk/services/chatService';
import {IndexedDB} from '../../storage/indexed-db';
import {TUI_BREAKPOINT, TuiButton, TuiLoader} from '@taiga-ui/core';
import {Oimg} from '../elements/oimg/oimg';
import {Router, RouterLink} from '@angular/router';
import {TranslatePipe} from '@ngx-translate/core';
import {LoadStatus, ServiceManager} from '../../service-manager';

@Component({
  selector: 'app-dm-list',
  imports: [
    TuiButton,
    Oimg,
    RouterLink,
    TranslatePipe,
    TuiLoader
  ],
  templateUrl: './dm-list.html',
  styleUrl: './dm-list.scss',
})
export class DmList implements OnInit {
  userid = input<string>("")
  token = input<string>("")

  indexedDb = inject(IndexedDB)
  router = inject(Router)
  serviceManager = inject(ServiceManager)
  breakpoint = inject(TUI_BREAKPOINT)

  async ngOnInit() {
    this.serviceManager.chatService = new ChatService(this.userid(), this.token(), this.indexedDb.getApi(), () => {})
    if (this.serviceManager.chatsStatus() != LoadStatus.loaded) {
      try {
        this.serviceManager.chats.set(await this.serviceManager.chatService.getQuick())
        this.serviceManager.chatsStatus.set(LoadStatus.updating)
      } catch (e) {
        console.warn(`Cache load failed: ${e}. Skipping cache load...`)
      }
      try {
        this.serviceManager.chats.set(await this.serviceManager.chatService.get())
        this.serviceManager.chatsStatus.set(LoadStatus.loaded)
      } catch (e) {
        console.error(e)
        this.serviceManager.chatsStatus.set(LoadStatus.error)
      }
    }
  }

  protected readonly LoadStatus = LoadStatus;
}
