//
//  RoomViewModel.swift
//  chat
//
//  Created by admin on 09.02.2022.
//

import Foundation
import RxSwift
import RxRelay

class RoomViewModel : BaseViewModel {
    
    private let postModule: PostModule
    private let userContext: UserContextProtocol
    
    private let messageViewModels: BehaviorRelay<[MessageViewModel]> = BehaviorRelay(value: [MessageViewModel]())
    
    init(postModule: PostModule, userContext: UserContextProtocol) {
        
        self.postModule = postModule
        self.userContext = userContext
        
        observableMessageViewModels = messageViewModels.asObservable()
    }
    
    var roomName: String = ""
    let sendButtonTitle = "send"
    var userMessage: String? = ""
    var observableMessageViewModels: Observable<[MessageViewModel]>
    
    override func onViewDidAppear() {
        postModule.updateRoomMessageHistory(room: roomName)
        
        postModule.onMessagesUpdated = { messageViewModels in
            if (messageViewModels.first?.room == self.roomName)
            {
                self.messageViewModels.accept(messageViewModels)
            }
        }
    }
    
    override func onViewDidDisappear() {
        
        postModule.onMessagesUpdated = nil
    }
    
    func send(message: String) {
        
        if (message.isEmpty) {
            return
        }   
        
        postModule.send(room: roomName, sender: userContext.getUsername(), message: message)
    }
}
