import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';
import 'package:qadirneyriz/utils/hive/local_user.dart';

class UserLocalDb {
  Box? initialbox;
  Box? box;
  bool isInitialized = false;

  initialized() async {
    if (!kIsWeb) {
      Directory appDocDirectory = await getApplicationDocumentsDirectory();
      var rootPath = Directory('${appDocDirectory.path}/dir');
      await rootPath.create(recursive: true);
      Hive.init(rootPath.path);
    }
    isInitialized = true;
  }

  openBox() async {
    await initialized();
    initialbox ??= await Hive.openBox('user_hive');
    return initialbox;
  }

  open() {
    box = Hive.box('user_hive');
    return box;
  }

  LocalUser getUser() {
    if (box == null) {
      open();
    }
    String name = box!.get('name', defaultValue: '');
    String token = box!.get('token', defaultValue: '');
    String mobile = box!.get('mobile', defaultValue: '');
    int role = box!.get('role', defaultValue: 0);
    List access = box!.get('access', defaultValue: []);
    String language = box!.get('language', defaultValue: 'en');

    return LocalUser(
        name: name,
        token: token,
        mobile: mobile,
        access: access,
        role: role,
        language: language);
  }

  saveUserField(String key, value) async {
    open();

    await box!.put(key, value);
  }

  void logOut() async {
    await openBox();
    await box!.clear(); // حذف تمامی داده‌ها از داخل box
    // Navigate to login screen
  }

  // Future<void> updateUser(LocalUser user) async {
  //   await openBox();
  //   box!.put('name', user.userName);
  //   box!.put('token', user.token);
  //   // box!.put('phone', user.phoneNumber);
  //   // box!.put('isLogin', user.isLogin);
  //   // box!.put('password', user.password);

  //   await initialbox!.put('name', user.userName);
  //   await initialbox!.put('token', user.token);
  //   // await initialbox!.put('phone', user.phoneNumber);
  //   // await initialbox!.put('isLogin', user.isLogin);
  //   // await initialbox!.put('password', user.password);
  // }
}
