using UnityEngine;
using MQTTnet;
using MQTTnet.Client;
using System;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

public class MqttCollector : MonoBehaviour
{
    private IMqttClient _mqttClient;
    private string _csvPath;

    [Header("Ustawienia MQTT")]
    public string brokerIp = "127.0.0.1";
    public int port = 1883;
    public string topic = "sensor/heartrate";

    // Funkcja wywoływana przez GameManager
    public async void BeginSession()
    {
        // 1. Stworzenie pliku CSV w folderze projektu
        string folder = Application.persistentDataPath + "/Sesje_Badawcze/";
        if (!Directory.Exists(folder)) Directory.CreateDirectory(folder);

        _csvPath = folder + "Dane_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".csv";
        File.WriteAllText(_csvPath, "Timestamp;Godzina;Tetno\n");

        Debug.Log($"<color=cyan>MQTT: Plik zapisu: {_csvPath}</color>");

        // 2. Konfiguracja MQTTnet
        var factory = new MqttFactory();
        _mqttClient = factory.CreateMqttClient();

        var options = new MqttClientOptionsBuilder()
            .WithTcpServer(brokerIp, port)
            .Build();

        // 3. Reakcja na odebraną wiadomość
        _mqttClient.ApplicationMessageReceivedAsync += e =>
        {
            string payload = Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment);
            SaveData(payload);
            return Task.CompletedTask;
        };

        // 4. Połączenie asynchroniczne
        try
        {
            await _mqttClient.ConnectAsync(options, CancellationToken.None);

            var subOptions = new MqttClientSubscribeOptionsBuilder()
            .WithTopicFilter(topic)
            .Build();

            await _mqttClient.SubscribeAsync(subOptions, CancellationToken.None);
            Debug.Log("<color=green>MQTT: Połączono i słucham tętna!</color>");
        }
        catch (Exception ex)
        {
            Debug.LogError($"MQTT Connection Error: {ex.Message}");
        }
    }

    private void SaveData(string json)
    {
        try
        {
            HeartRateData data = JsonUtility.FromJson<HeartRateData>(json);

            // Format: Data i czas ; tętno
            string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            string line = $"{timestamp};{data.hr}\n";

            File.AppendAllText(_csvPath, line);
            Debug.Log($"<color=white>Zapisano HR: {data.hr}</color>");
        }
        catch (Exception ex)
        {
            Debug.LogWarning($"Błąd parsowania: {json}. Szczegóły: {ex.Message}");
        }
    }

    private async void OnApplicationQuit()
    {
        if (_mqttClient != null) await _mqttClient.DisconnectAsync();
    }
}