package com.dspread.pos.common.websocket;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class WebSocketViewModel extends ViewModel implements WebSocketManager.WebSocketListener {
    private WebSocketManager webSocketManager;
    private MutableLiveData<String> messageLiveData = new MutableLiveData<>();
    private MutableLiveData<Boolean> connectionStatus = new MutableLiveData<>();
    private MutableLiveData<String> errorLiveData = new MutableLiveData<>();

    public WebSocketViewModel() {
        webSocketManager = new WebSocketManager(this);
    }

    public void connectToServer(String serverUrl) {
        webSocketManager.connect(serverUrl);
    }

    public void sendMessage(String message) {
        webSocketManager.sendMessage(message);
    }

    public void disconnect() {
        webSocketManager.disconnect();
    }

    public LiveData<String> getMessageLiveData() {
        return messageLiveData;
    }

    public LiveData<Boolean> getConnectionStatus() {
        return connectionStatus;
    }

    public LiveData<String> getErrorLiveData() {
        return errorLiveData;
    }

    @Override
    public void onMessageReceived(String message) {
        messageLiveData.postValue(message);

        // Auto-reply to "Message 1 from Server"
        if ("Message 1 from Server".equals(message)) {
            webSocketManager.sendMessage("Message 2 from Android");
        }
    }

    @Override
    public void onConnectionEstablished() {
        connectionStatus.postValue(true);
    }

    @Override
    public void onConnectionClosed() {
        connectionStatus.postValue(false);
    }

    @Override
    public void onError(String error) {
        errorLiveData.postValue(error);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        webSocketManager.disconnect();
    }
}