import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject, Observable } from 'rxjs';
import { ChatConversation } from 'app/chat/models/chat-conversation';
import { ChatUser } from 'app/chat/models/chat-user';
import { ChatService } from 'app/chat/services/chat.service';
import { UserService } from 'app/services/user.service';

@Injectable()
export class ChatUiService {

  // private _conversations: ChatConversation[] = [];
  private _conversations: BehaviorSubject<ChatConversation[]> = new BehaviorSubject([]);
  public readonly conversations: Observable<ChatConversation[]> = this._conversations.asObservable();

  private get userId(): number {
    return this.userService.userInfo().userInfoMstrId;
  }

  constructor(
    private chatService: ChatService,
    private userService: UserService
  ) { }

  startConversation(user: ChatUser) {
    // if the conversation already exsists do not start a new one
    if (this.conversationWithUserExists(user)) {
      this.log('conversation found for user', user);
      return;
    }

    if (user.conversationId) {
      this.chatService.getConversation(user.conversationId).subscribe((conversation: ChatConversation) => this.addConversation(conversation));
    } else {
      this.chatService.startConversation(user.id).subscribe((conversation: ChatConversation) => this.addConversation(conversation));
    }

    let newConversation = { user, id: user.conversationId, messages: null } as ChatConversation;

  }

  closeConversation(conversation: ChatConversation) {
    let conversations = this._conversations.getValue();
    let index = conversations.indexOf(conversation);
    conversations.splice(index, 1);
    this._conversations.next(conversations);
  }

  private conversationWithUserExists(user: ChatUser) {
    return this._conversations.getValue().find(conversation => conversation.user.id == user.id);
  }

  private addConversation(conversation: ChatConversation) {
    let conversations = this._conversations.getValue();
    conversations.push(conversation);
    this._conversations.next(conversations);
  }

  private log(...args) {
    console.log('chat-ui-service:', ...args);
  }
}