import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:sfm_app/product/cache/local_manager.dart';
import 'package:sfm_app/product/constant/app/api_path_constant.dart';
import 'package:sfm_app/product/constant/enums/local_keys_enums.dart';
import 'package:sfm_app/product/network/network_manager.dart';
import '../product/base/bloc/base_bloc.dart';
import '../product/services/api_services.dart';
import '../feature/bell/bell_model.dart';
import '../feature/settings/profile/profile_model.dart';
import '../product/shared/shared_snack_bar.dart';

class MainBloc extends BlocBase {
  APIServices apiServices = APIServices();
  final bellBloc = StreamController<Bell>.broadcast();
  StreamSink<Bell> get sinkBellBloc => bellBloc.sink;
  Stream<Bell> get streamBellBloc => bellBloc.stream;

  final language = StreamController<Locale?>.broadcast();
  StreamSink<Locale?> get sinkLanguage => language.sink;
  Stream<Locale?> get streamLanguage => language.stream;

  final theme = StreamController<ThemeData?>.broadcast();
  StreamSink<ThemeData?> get sinkTheme => theme.sink;
  Stream<ThemeData?> get streamTheme => theme.stream;

  final themeMode = StreamController<bool>.broadcast();
  StreamSink<bool> get sinkThemeMode => themeMode.sink;
  Stream<bool> get streamThemeMode => themeMode.stream;

  final isVNIcon = StreamController<bool>.broadcast();
  StreamSink<bool> get sinkIsVNIcon => isVNIcon.sink;
  Stream<bool> get streamIsVNIcon => isVNIcon.stream;

  final userProfile = StreamController<User>.broadcast();
  StreamSink<User> get sinkUserProfile => userProfile.sink;
  Stream<User> get streamUserProfile => userProfile.stream;

  @override
  void dispose() {}

  void getUserProfile(BuildContext context) async {
    try {
      User user = await apiServices.getUserDetail();
      sinkUserProfile.add(user);
    } catch (e) {
      if (!context.mounted) return;
      showErrorTopSnackBarCustom(
          context, e.toString());
    }

  }

  getFCMTokenAndPresentations() async {

    String? firebaseAppToken = await FirebaseMessaging.instance.getToken();

    if (firebaseAppToken != null) {
      log("FCM TOKEN: $firebaseAppToken");
      sendNotificationToken(firebaseAppToken);
    } else {
      log("FCM TOKEN: null");
    }
  }

  Future<int> sendNotificationToken(String token) async{
    String uid = await getUID();
    Map<String,dynamic> body = {
      "user_id": uid,
      "app_token": token
    };
    int statusCode = await NetworkManager.instance!.updateDataInServer(
        APIPathConstants.NOTIFICATION_TOKEN_PATH, body);
    return statusCode;
  }

  Future<String> getUID() async {
    String uid = LocaleManager.instance.getStringValue(PreferencesKeys.UID);
    return uid;
  }
}
