import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;

class FileProcess {
  static bool isFolderCreated = false;
  static Directory? directory;

  static Future checkDocumentFolder() async {
    try {
      if (!isFolderCreated) {
        directory = await getApplicationDocumentsDirectory();
        await directory!.exists().then((value) {
          if (value) directory!.create();
          isFolderCreated = true;
        });
      }
    } catch (e) {
      print(e.toString());
    }
  }

  static void openFile(String fileName, {bool isFullPath = false}) {
    String dir = directory!.path + "/$fileName.pdf";
    OpenFilex.open(isFullPath ? fileName : dir);
  }

  static Future<File> downloadFile(String base64Content, String fileName) async {
    Uint8List bytes = base64.decode(base64Content);
    await checkDocumentFolder();
    String dir = directory!.path + "/" + fileName + ".pdf";
    File file = File(dir);
    if (!file.existsSync()) file.create();
    await file.writeAsBytes(bytes);
    return file;
  }

  static Future<String> downloadFileFromUrl(String url,String fileName) async {
    await checkDocumentFolder();
    String filePath = '${directory!.path}/$fileName';

    if (await File(filePath).exists()) {
      await Future.delayed(const Duration(seconds: 1));
      return filePath;
    } else {
      var response = await http.get(Uri.parse(url));
      if (response.statusCode == 200) {
        var bytes = response.bodyBytes;
        File file = File(filePath);
        await file.writeAsBytes(bytes);
        return filePath;
      } else {
        throw Exception('Failed to download file');
      }
    }
  }
}
