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

import 'package:get_storage/get_storage.dart';

import '../../features/auth/data_layer/model/user.dart';
import '../../features/card/data_layer/model/appointment.dart';

class LocalStorage {
  final GetStorage storage = GetStorage();

  Future<void> saveUser(User user) async {
    await storage.write("user", user.toJson());
  }

  Future<void> saveLanguage(String langCode) async {
    await storage.write("language", langCode);
  }

  String? getLanguage() {
    return storage.read("language");
  }

  User? getUser() {
    return User.fromJson(storage.read("user"));
  }

  Future<void> saveIsGuest(bool isGuest) async {
    await storage.write('isGuest', isGuest);
  }

  bool? getIsGuest() {
    return storage.read('isGuest');
  }

  Future<void> savefirstTimeOpened() async {
    await storage.write('firstTime', false);
  }

  bool getfirstTimeOpened() {
    return storage.read('firstTime') ?? true;
  }

  Future<void> saveToken(String token) async {
    await storage.write("token", token);
  }

  String? getToken() {
    return storage.read("token");
  }

  Future<void> saveFCMToken(String fcmToken) async {
    await storage.write('fcm_token', fcmToken);
  }

  String? getFCMToken() {
    String? fcmToken = storage.read('fcm_token');
    log('my fcm token : $fcmToken');
    return fcmToken;
  }

  Future<void> saveChatToken(String chatToken) async {
    await storage.write("chat_token", chatToken);
  }

  String? getChatToken() {
    return storage.read("chat_token");
  }

  Future<void> saveChatUserId(int chatUserId) async {
    await storage.write("chat_user_id", chatUserId);
  }

  int? getChatUserId() {
    return storage.read("chat_user_id");
  }

  Future<void> clearCache() async {
    await storage.erase();
  }

  Future<void> setAppointments(List<Appointment> appointments) async {
    for (int i = 0; i < appointments.length; i++) {
      await storage.write(
          'appointments[$i]', jsonEncode(appointments[i].toJson()));
    }
    await storage.write('appointments_length', appointments.length);
  }

  List<Appointment>? getAppointments() {
    int appointmentsLength = storage.read('appointments_length') ?? 0;
    if (appointmentsLength == 0) {
      return null;
    } else {
      List<Appointment> appointments = [];
      for (int i = 0; i < appointmentsLength; i++) {
        appointments.add(
          Appointment.fromJson(
            jsonDecode(
              storage.read('appointments[$i]'),
            ),
          ),
        );
      }
      return appointments;
    }
  }
}
