import 'dart:io';

import 'package:flutter/widgets.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class CompassImageProvider extends ChangeNotifier {
  CompassImageProvider() {
    loadCompassImage();
  }

  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  ImageProvider _rotateImage;

  ImageProvider get rotateImage => _rotateImage;

  //  加载罗盘图片
  void loadCompassImage() async {
    final appDataDirectory = await getApplicationDocumentsDirectory();
    File file = File(join(appDataDirectory.path, 'rotate_image'));
    bool isFileExist = await file.exists();
    if (isFileExist) {
      _rotateImage = FileImage(file);
    } else {
      _rotateImage = null;
    }
    notifyListeners();
  }

  void setSelectedRotateImage(XFile res) async {
    final appDataDirectory = await getApplicationDocumentsDirectory();
    String pathString = res.name;
    if (pathString == null) {
      return;
    }
    res.saveTo(join(appDataDirectory.path, 'rotate_image'));
    File file = File(res.path);
    var isFileExist = await file.exists();
    if (isFileExist) {
      _rotateImage = FileImage(file);
    } else {
      _rotateImage = null;
    }
    notifyListeners();
  }

  // 将罗盘图片重置为默认
  void resetRotateImage() async {
    final appDataDirectory = await getApplicationDocumentsDirectory();
    File file = File(join(appDataDirectory.path, 'rotate_image'));
    bool isFileExist = await file.exists();
    if (isFileExist) {
      file.delete();
    }
    _rotateImage = null;
    notifyListeners();
  }
}
