import 'dart:io';

import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';

class FileCacheMgr {
  static const key = "libCachedImageData";

  static FileCacheMgr _instance;

  /// The DefaultCacheManager that can be easily used directly. The code of
  /// this implementation can be used as inspiration for more complex cache
  /// managers.
  factory FileCacheMgr() {
    if (_instance == null) {
      _instance = new FileCacheMgr._();
    }
    return _instance;
  }

  FileCacheMgr._();

  Future<String> getFilePath() async {
    var directory = await getTemporaryDirectory();
    return p.join(directory.path, key);
  }

  Future<String> genFilePath(String fileId) async {
    var filePath = p.join(await getFilePath(), fileId);
    var folder = new File(filePath).parent;
    if (!(await folder.exists())) {
      folder.createSync(recursive: true);
    }
    return filePath;
  }

  Future<File> writeFile(String fileId,  fileBytes) async {
    var path = p.join(await getFilePath(), fileId);
    print('receive path : $path');
    var folder = new File(path).parent;
    if (!(await folder.exists())) {
      folder.createSync(recursive: true);
    }
    var file = await File(path).writeAsBytes(fileBytes);

    return file;
  }



  Future<File> getFile(String fileId) async {
    var filePath = p.join(await getFilePath(), fileId);
    var file = File(filePath);
    if (await file.exists()) {
      return file;
    }
    return null;
  }


  static  String pathKey;
  static initPathKey()async{
    if(pathKey==null && Platform.isIOS){
      Directory dir = await getTemporaryDirectory();
      String path =dir.path;
      int start = path.indexOf('Application')+12;
      int end = start+36;
      pathKey = path.substring(start,end);
    }
  }
  ///给ios文件路径替换成正确的
  static replacePath(String filePath) {
    if(Platform.isIOS && filePath!=null){
//      print('filePath $filePath');
      int start =  filePath.indexOf('Application')+12;
      int end = start+36;
      filePath = filePath.replaceRange(start, end, pathKey);
//      print('after :  $gg');

    }
    return filePath;
  }


}
