// ignore_for_file: unused_catch_clause

import 'dart:io';

import 'package:byod/bloc/view_bill.dart';
import 'package:byod/helper/logger.dart';
import 'package:byod/main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:mqtt_client/mqtt_browser_client.dart';
import 'package:mqtt_client/mqtt_client.dart';
import 'package:uuid/uuid.dart';

String mqttUrl = 'wss://mq.jasadigital.co.id';

final mqClient = MqttBrowserClient(mqttUrl, '');
const int mqttPort = 8083;
const String queueTopic = 'romi/byod/payment';
// String queueMessage = getMqMessage();
const String usernameMq = 'jasadigital';
const String passwordMq = 'jasadigital';
const uuidInit = Uuid();
var uuid = uuidInit.v4();

Future<int> runMqTT(BuildContext context) async {
  mqClient.logging(on: false);
  mqClient.setProtocolV311();
  mqClient.keepAlivePeriod = 86400;
  mqClient.port = mqttPort;
  mqClient.onDisconnected;
  mqClient.onConnected;
  mqClient.onSubscribed;
  // mqClient.pongCallback = pong;

  final connMess = MqttConnectMessage()
      .withClientIdentifier(uuid)
      .withWillTopic('willtopic') // If you set this you must set a will message
      .withWillMessage('My Will message')
      .startClean() // Non persistent session for testing
      .withWillQos(MqttQos.atLeastOnce);
  // print('EXAMPLE::Mosquitto client connecting....');
  mqClient.connectionMessage = connMess;

  try {
    await mqClient.connect(usernameMq, passwordMq);
  } on NoConnectionException catch (e) {
    if (debug) {
      logd('MQ CONFIG::client exception', '$e');
    }
    mqClient.disconnect();
  } on SocketException catch (e) {
    if (debug) {
      logd('MQ CONFIG::socket exception', '$e');
    }
    mqClient.disconnect();
  }
  if (mqClient.connectionStatus!.state == MqttConnectionState.connected) {
    if (debug) {
      logd('CHECK CONNECTION', 'CONNECTED');
    }
  } else {
    /// Use status here rather than state if you also want the broker return code.
    // print(
    //     'EXAMPLE::ERROR Mosquitto client connection failed - disconnecting, status is ${mqClient.connectionStatus}');
    mqClient.disconnect();
    exit(-1);
  }

  /// Ok, lets try a subscription
  // print('EXAMPLE::Subscribing to the queuetest/1 topic');
  var topic = queueTopic; // Not a wildcard topic
  mqClient.subscribe(topic, MqttQos.atMostOnce);

  /// The client has a change notifier object(see the Observable class) which we then listen to to get
  /// notifications of published updates to each subscribed topic.
  mqClient.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
    final recMess = c![0].payload as MqttPublishMessage;
    final pt =
        MqttPublishPayload.bytesToStringAsString(recMess.payload.message);
    // print('Notifikasi masuk dari topic <${c[0].topic}>, isinya adalah: $pt ');
    // print('');
    if (c[0].topic == topic && pt.contains("ORDER-ID")) {
      // update bill disini
      String sessionID = prefs.getString('sessionId') ?? '';
      if (sessionID != '' && pt.contains(sessionID)) {
        context.read<ViewBillBloc>().getBill();
      }
      if (debug) {
        logd('CHECK TOPIC', 'TOPIC MASUK::${c[0].topic} , MESSAGE::$pt');
      }
    } else {
      if (debug) {
        logd('CHECK TOPIC',
            'TOPIC TIDAK SAMA, YANG MASUK::$topic , MESSAGE::$pt');
      }
    }
  });
  // final builder = MqttClientPayloadBuilder();
  // builder.addString('Hello from mqtt_client');
  // mqClient.publishMessage(topic, MqttQos.exactlyOnce, builder.payload!);
  return 0;
}
