import 'dart:convert';

import 'package:get/get.dart';
import 'package:vnote_device_plugin/consts/types.dart';
import 'package:vitalapp/architecture/storage/text_storage.dart';
import 'package:vitalapp/managers/interfaces/models/device.dart';

import 'interfaces/device.dart';
import 'interfaces/system_setting.dart';

class DeviceManager extends IDeviceManager {
  static final _typeConvertMap = <String, String>{
    "Temp": DeviceTypes.TEMP,
    "Weight": DeviceTypes.WEIGHT,
    "SpO2": DeviceTypes.SPO2,
    "NIBP": DeviceTypes.NIBP,
    "GLU": DeviceTypes.SUGAR,
    // "ECG": DeviceTypes.HEART,
  };
  final _storage = TextStorage(fileName: "devices.cfg");
  List<DeviceModel>? _cacheList;

  @override
  Future<List<String>> getAccessTypes() async {
    final settings = await Get.find<ISystemSettingManager>().getSettings();
    final settingTypes = settings.peripheralDevice!.split(',');
    final types = settingTypes
        .map((e) => _typeConvertMap[e])
        .where((e) => e != null)
        .map((e) => e!)
        .toList();
    return types;
  }

  @override
  Future<void> addDevice(DeviceModel model) async {
    final source = await getDeviceList();
    final list = List<DeviceModel>.from(source);

    list.removeWhere((e) => e.type == model.type);
    list.add(model);

    saveDeviceList(list);
  }

  @override
  Future<void> removeDeviceByType(String type) async {
    final source = await getDeviceList();
    final list = List<DeviceModel>.from(source);

    list.removeWhere((e) => e.type == type);

    saveDeviceList(list);
  }

  @override
  Future<List<DeviceModel>> getDeviceList() async {
    if (_cacheList != null) return _cacheList!;

    final jsonText = await _storage.read();
    if (jsonText == null) {
      _cacheList = [];
    } else {
      final List<dynamic> mapList = jsonDecode(jsonText);
      _cacheList = mapList.map((e) => DeviceModel.fromJson(e)).toList();
    }
    return _cacheList!;
  }

  @override
  Future<void> saveDeviceList(List<DeviceModel> deviceList) async {
    _cacheList = deviceList;
    final jsonText = jsonEncode(deviceList);
    await _storage.save(jsonText);
  }
}
