import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})
export class OperatorschatDataService {

  // Initial data
  private dataSubject = new BehaviorSubject<any>({
    dataUpdate: null,
    typing: null,
    conversationUpdate : null,
    writing : []
  });
  // Observable for the data
  data$ = this.dataSubject.asObservable();

sidemenuUpdate(data){
  
}
// Method to update writing
updateWriting(res: any) {  
  const currentState = this.dataSubject.value;
  let currentUsersTyping = this.dataSubject.value?.writing;
  const index = currentUsersTyping.findIndex(e => e.userId === res.userId);
  if (index !== -1) {
    // User with the same userId exists, so update the existing entry
    currentUsersTyping[index] = res;
  } else {
    // User with the same userId does not exist, so push the new entry
    currentUsersTyping.push(res);
  }
  this.dataSubject.next({
    ...currentState,
    conversationUpdate: {livechatdata: {}},
    writing: currentUsersTyping,
  });
}
  removeWriting(id){
    const currentState = this.dataSubject.value;
    let currentUsersTyping = this.dataSubject.value?.writing;
    currentUsersTyping = currentUsersTyping.filter(e => e.userId != id);
    this.dataSubject.next({
      ...currentState,
      conversationUpdate: {livechatdata: {}},
      writing: currentUsersTyping,
    });
  }
  clearWriting(){
    const currentState = this.dataSubject.value;
    this.dataSubject.next({
      ...currentState,
      conversationUpdate: {livechatdata: {}},
      writing: [],
    });
  }
}
