
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:wallpaper/utils/dbmanager.dart';
import 'package:wallpaper/utils/local_img_manager.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:async_wallpaper/async_wallpaper.dart';

class DownloadManager {
  static Future<bool> downloadImgWithUrl(String urlStr) async {
    //对于android先去判断存储权限的获取
    // if (!await Permission.storage.request().isGranted) {
    //     return false;
    // }

    // await Permission.photos.request();

    // Permission.photos.

    var httpClient = HttpClient();
    try {
      // option: Options(responseType: ResponseType.bytes)
      var reqiest = await httpClient.getUrl(Uri.parse(urlStr));
      var response = await reqiest.close();
      var bytes = await consolidateHttpClientResponseBytes(response);
      var fileName = await LocalImgManager.saveImgDataBytes(bytes);
      // print(fileName);
      //写入数据库信息
      DBManager.addImg(fileName);
      return true;
    }
    catch(error) {
      print("the error:${error}");
      return true;
    }
  }


  // 保存到相册的UTil

  // static Future<dynamic> saveLocalImage(String imagePath) async {
    // var image = await ImageUtil.loadImageByFile(imagePath);
    // ByteData? byteData =
    // await (image.toByteData(format: ui.ImageByteFormat.png));
    // if (byteData != null) {
    //   final result =
    //   await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
    //   print("SaveToAlbumUtil result:${result}");
    //   return result;
    // } else {
    //   throw StateError("saveLocalImage error imagePath:${imagePath}");
    // }
  // }

//从网络保存至相册
  static Future<void>  saveNetworkImage(String urlStr) async {
    var httpClient = HttpClient();
    var reqiest = await httpClient.getUrl(Uri.parse(urlStr));
    var response = await reqiest.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    await ImageGallerySaver.saveImage(
        Uint8List.fromList(bytes),
        quality: 60,
        name: "hello");
  }

  //把本地图片保存至相册
  static Future<void>  saveLocalImage(String urlStr) async {

    // 获取图片文件
    final imageFile = File(urlStr);
    // 保存图片到相册
    await ImageGallerySaver.saveFile(imageFile.path);
  }


//android设置壁纸
  static Future<bool> setWallpaper(String urlStr) async {
      bool result;
      try {
          result = await AsyncWallpaper.setWallpaper(
                      url: urlStr,
                      wallpaperLocation: AsyncWallpaper.HOME_SCREEN,
                      goToHome: false,
                      // toastDetails: ToastDetails.success(),
                      // errorToastDetails: ToastDetails.error(),
                    );
          print("result:$result ");
      } on PlatformException {
          result = false;
          print("err  ....result:$result ");
      }
      return result;
  }

//从本地图片设置壁纸
  static Future<bool> setWallpaperNative(String urlStr) async {
      bool result;
      try {
          result = await AsyncWallpaper.setWallpaperFromFile(
                      filePath: urlStr,
                      wallpaperLocation: AsyncWallpaper.HOME_SCREEN,
                      goToHome: false,
                      // toastDetails: ToastDetails.success(),
                      // errorToastDetails: ToastDetails.error(),
                    );
          print("result:$result ");
      } on PlatformException {
          result = false;
          print("err  ....result:$result ");
      }
      return result;
  }

//删除本地图片
static Future<void> deleteWallpaperFile(String urlStr) async{
  // 删除文件
  final file = File(urlStr);
  if (await file.exists()) {
    await file.delete();
    print('文件已删除：$urlStr');
  } else {
    print('文件不存在：$urlStr');
  }
}
  


}