import {Component, inject, OnInit, signal} from '@angular/core';
import {DmStorage, ServiceManager} from '../../service-manager';
import {ActivatedRoute} from '@angular/router';
import {DMService} from '@chatenium/chatenium-sdk/services/dmService';
import {IndexedDB} from '../../storage/indexed-db';
import {Navbar} from '../elements/navbar/navbar';
import {Oimg} from '../elements/oimg/oimg';
import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core';
import {FileDataWithPreview, MessageBox} from '../elements/message-box/message-box';
import {Messages} from '../elements/messages/messages';
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema';
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
import {MessageBoxViewModel} from '../elements/message-box/message-box-viewmodel';
import {WebSocketHandler} from '@chatenium/chatenium-sdk/core/webSocketHandler';
import {FileData, FileUploadProgressListener} from '@chatenium/chatenium-sdk/domain/fileUploadService.schema';
import {Attachment} from '@chatenium/chatenium-sdk/domain/common.schema';

@Component({
  selector: 'app-dm',
  imports: [
    Navbar,
    Oimg,
    TuiButton,
    TuiIcon,
    MessageBox,
    Messages
  ],
  templateUrl: './dm.html',
  styleUrl: './dm.scss',
})
export class Dm implements OnInit {
  serviceManager = inject(ServiceManager)
  route = inject(ActivatedRoute)
  indexedDb = inject(IndexedDB)
  breakpoint = inject(TUI_BREAKPOINT)

  chatid = ""

  get store(): DmStorage {
    return this.serviceManager.dmServices()[this.chatid]
  }

  async sendMessage(message: string, files: FileDataWithPreview[] | null) {
    if (!files && message.trim() == "") return

    const session = this.serviceManager.currentSession();
    if (session != null) {
      const editedMessage = this.store.messageBox.editingMessage()
      if (editedMessage) {
        const storedMsg = this.store.messages().find(m => m.msgid == editedMessage.messageId)
        const originalMessage: Message = JSON.parse(JSON.stringify(storedMsg))
        if (storedMsg) {
          storedMsg.message = message
        }

        try {
          await this.store.service.editMessage(editedMessage.messageId, message)
        } catch (e) {
          if (storedMsg) {
            storedMsg.message = originalMessage.message
          }
        }

        this.store.messageBox.editingMessage.set(null)
        this.store.messageBox.message.set("")
        return
      }

      let attachments: Attachment[] = []
      files?.forEach(file => {
        const extraMetaData: Record<string, string> = {}
        extraMetaData["thumbnailMetaData"] = file.videoThumbnail ?? ""

        attachments.push({
          fileName: file.name,
          fileId: file.fileId,
          type: file.type,
          format: file.extension,
          path: file.blob,
          height: file.height,
          width: file.width,
          extraMetaData: extraMetaData
        })
      })

      this.store.messages.update(value => [...value, {
        message: message,
        chatid: this.chatid,
        files: attachments,
        replyTo: "",
        author: session.userData.userid,
        seen: false,
        msgid: "",
        forwardedFrom: "",
        isEdited: false,
        sent_at: {T: 0, I: 0},
        replyToId: "",
        forwardedFromName: ""
      }])

      this.scrollToBottom("smooth")

      await this.store.service.sendMessage("", message, null, null, files, <FileUploadProgressListener>{
        fileProgressUpdate: (tempMsgId, fileId, allChunks, chunksDone) => {
          this.uploadProgressUpdate(tempMsgId, fileId, allChunks, chunksDone)
        }
      })
    }

    this.store.messageBox.message.set("")
  }

  async deleteMessage(messageId: string) {
    const i = this.store.messages().findIndex(m => m.msgid == messageId)
    if (i != -1) {
      const originalMessage: Message = JSON.parse(JSON.stringify(this.store.messages()[i]))
      this.store.messages().splice(i, 1)
      try {
        await this.store.service.deleteMessages([messageId])
      } catch (e) {
        this.store.messages().splice(i, 0, originalMessage)
      }
    }
  }

  scrollToBottom(anim: 'instant' | 'smooth'): void {
    setTimeout(() => {
      const scrollContainer = <HTMLDivElement>document.querySelector("#scrollContainer")
      scrollContainer.scroll({
        top: scrollContainer.scrollHeight,
        left: 0,
        behavior: anim
      });
    }, 0)
  }

  uploadProgressUpdate(tempMsgId: string, fileId: string, allChunks: number, chunksDone: number) {
    console.log(fileId, allChunks, chunksDone)
  }

  // The chatid parameter ensures isolation
  onWsListen(action: string, message: string, chatid: string) {
    const data = JSON.parse(message);
    if (data.chatid === chatid) {
      const targetStore = this.serviceManager.dmServices()[chatid];
      if (targetStore) {
        switch (action) {
          case "newMessage":
            targetStore.messages.update(messages => [...messages, data]);
            this.scrollToBottom("smooth")
            break;
        }
      }
    }
  }

  ngOnInit() {
    this.route.params.subscribe(async params => {
      const chatid = params['chatid'];
      this.chatid = chatid;

      const session = this.serviceManager.currentSession();
      const chatData = this.serviceManager.chats().find(c => c.chatid === chatid);

      if (!session || !chatData) {
        return
      }

      if (!this.serviceManager.dmServices()[chatid]) {
        const newStore = {
          chatData: signal<Chat>(chatData),
          messages: signal<Message[]>([]),
          messageBox: new MessageBoxViewModel((msg, files) => this.sendMessage(msg, files)),
          wsListener: (action, data) => this.onWsListen(action, data, chatid),
        } as DmStorage;

        newStore.service = new DMService(
          session.userData.userid,
          session.token,
          chatid,
          this.indexedDb.getApi(),
          (action, data) => newStore.wsListener(action, data)
        );

        this.serviceManager.dmServices()[chatid] = newStore;

        const currentStore = this.serviceManager.dmServices()[chatid];
        const history = await currentStore.service.get();
        currentStore.messages.set(history);
        this.scrollToBottom("instant")

        await currentStore.service.joinWebSocketRoom();
      }
    });
  }
}
