import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { Router } from '@angular/router';
import { ActivatedRoute } from '@angular/router';

import { FormsModule } from '@angular/forms';
import Parse from "parse";

@Component({
  selector: 'app-chat',
  templateUrl: 'chat.page.html',
  styleUrls: ['chat.page.scss']
})
export class ChatPage implements OnInit{
  userid: string;
  messageList:any = []
  messages = [
    { type: 'received', avatar: '/assets/img/female.png', time: '10:30 AM', text: 'Hi there!' },
    { type: 'sent', avatar: '/assets/img/female.png', time: '10:31 AM', text: 'Hey! How are you?' },
    // Add more messages as needed
  ];
  
  newMessage: string = '';

  constructor(private route: ActivatedRoute) {
    this.userid = this.route.snapshot.paramMap.get('userid') as string;
    this.targetId = this.userid
  }

  contact:Parse.Object|undefined
  user:Parse.User|undefined
  targetId:string |undefined
  async ngOnInit() {
    this.user =  Parse.User.current()
    let fromId = Parse.User.current()?.id
    if(this.userid && fromId){
      let query = new Parse.Query("Contact");
      query.include("to")
      query.equalTo("from",fromId);
      query.equalTo("to",this.userid);
      this.contact = await query.first();
    }
    this.loadHistory();
    return
  }
  async sendMessage() {
    if (this.newMessage.trim() === '') {
      return;
    }
    let sendUser = Parse.User?.current()?.toPointer()
    let receiveUser = {__type:"Pointer",className:"_User",objectId:this.userid}
    let Message = Parse.Object.extend("Message");
    let message = new Message();
    message.set("sendUser",sendUser)
    message.set("receiveUser",receiveUser)
    message.set("contentJson",{
      role:"user",
      content: this.newMessage
    })
    message = await message.save()
    if(message?.id){
      this.messageList.push(message)
      this.syncSession(message,sendUser,receiveUser);
    }
    this.newMessage = '';

    this.loadHistory();
  }
  async syncSession(message:any,sendUser:any,receiveUser:any){
    // 根据当前聊天，更新最新的会话状态表 MessageSession 记录最新的会话
    let session = await this.checkSessionExists();
    if(!session?.id){
      let MessageSession = Parse.Object.extend("MessageSession")
      session = new MessageSession()
    }
    session?.set("message",message?.toPointer())
    session?.set("sendUser",sendUser)
    session?.set("receiveUser",receiveUser)
    session?.save();
  }
  async checkSessionExists(){
    let query = Parse.Query.fromJSON('MessageSession',{where: {
      $or: [
        {
          sendUser: this.user?.id,
          receiveUser: this.targetId
        },
        {
          sendUser: this.targetId,
          receiveUser: this.user?.id
        }
      ]
    }})
    return await query.first()
  }

  getCurrentTime() {
    const now = new Date();
    return now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  }

  async loadHistory(){
    let query = Parse.Query.fromJSON('Message',{where: {
      $or: [
        {
          sendUser: this.user?.id,
          receiveUser: this.targetId
        },
        {
          sendUser: this.targetId,
          receiveUser: this.user?.id
        }
      ]
    }})

    let list = await query.find();
    if(list?.length){
      this.messageList = list
    }
  }
}