/*
 * 聊天历史服务
 * 用于在本地记录用户与谁聊过天，并在新会话登录时获取历史记录
 */

import {logger} from '../logger';
import rootScope from '../rootScope';

/**
 * 聊天对象记录
 */
interface ChatPeer {
  peerId: string; // 聊天对象ID
  lastChatTime: number; // 最后聊天时间戳
}

/**
 * 聊天历史服务类
 */
export class ChatHistoryService {
  private log = logger('chat-history-service');
  private readonly STORAGE_KEY = 'chat_history_peers';
  private readonly MAX_PEERS = 50;

  /**
   * 记录聊天对象ID
   * @param peerId 聊天对象ID
   */
  public recordChatPeer(peerId: string | number): void {
    try {
      const peerIdStr = peerId.toString();
      const now = Date.now();

      // 获取现有记录
      const existingPeers = this.getChatPeers();

      // 检查是否已存在该peerId
      const existingIndex = existingPeers.findIndex(p => p.peerId === peerIdStr);

      if(existingIndex !== -1) {
        // 更新最后聊天时间
        existingPeers[existingIndex].lastChatTime = now;
      } else {
        // 添加新记录
        existingPeers.push({
          peerId: peerIdStr,
          lastChatTime: now
        });
      }

      // 按最后聊天时间排序（降序）
      existingPeers.sort((a, b) => b.lastChatTime - a.lastChatTime);

      // 限制记录数量
      const limitedPeers = existingPeers.slice(0, this.MAX_PEERS);

      // 保存回localStorage
      this.saveChatPeers(limitedPeers);
    } catch(error) {
      this.log('记录聊天对象ID失败:', error);
    }
  }

  /**
   * 聊天对象ID是否存在
   * @param peerId 聊天对象ID
   * @returns 是否存在
   */
  public hasChatPeer(peerId: string | number): boolean {
    const chatPeers = this.getChatPeers();
    const hasPeer = chatPeers.find(peer => peer.peerId === peerId.toString()) !== undefined;
    this.log(`${peerId} exists: ${hasPeer}`);
    return hasPeer;
  }

  /**
   * 获取所有记录的聊天对象
   */
  public getChatPeers(): ChatPeer[] {
    try {
      const peersJson = localStorage.getItem(this.STORAGE_KEY);
      if(!peersJson) return [];

      return JSON.parse(peersJson);
    } catch(error) {
      this.log('获取聊天对象记录失败:', error);
      return [];
    }
  }

  /**
   * 保存聊天对象记录
   */
  private saveChatPeers(peers: ChatPeer[]): void {
    try {
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(peers));
    } catch(error) {
      this.log('保存聊天对象记录失败:', error);
    }
  }

  /**
   * 清除所有聊天对象记录
   */
  public clearChatPeers(): void {
    try {
      localStorage.removeItem(this.STORAGE_KEY);
    } catch(error) {
      this.log('清除聊天对象记录失败:', error);
    }
  }
}

// 导出单例实例
export const chatHistoryService = new ChatHistoryService();
