
import 'package:receive_sharing_intent/receive_sharing_intent.dart';

import 'MessageMgr.dart';

class ReceiveShareFile {
  static String tempFilePath;

  static int mLastClickTime = 0;
  static int timeInterval = 3000;

  static void init() {
// For sharing images coming from outside the app while the app is in the memory
     ReceiveSharingIntent.getMediaStream()
        .listen((List<SharedMediaFile> value) {

      if (currentIndex == 1) {
        int nowTime = DateTime.now().millisecondsSinceEpoch;

        if (nowTime - mLastClickTime > timeInterval) {
          if (value != null && value.length > 0) {
            MessageMgr().emit(MessageMgr.RECEIVE_THIRD_SHARE, value[0].path);
            mLastClickTime = nowTime;
          }
        }
      } else {
//      print("### 记录下来了1");
        if (value != null && value.length > 0) {
          tempFilePath = value[0].path;
        }
      }
    }, onError: (err) {
      print("getIntentDataStream error: $err");
    });

    // For sharing images coming from outside the app while the app is closed
    ReceiveSharingIntent.getInitialMedia().then((List<SharedMediaFile> value) {
//      setState(() {
//        _sharedFiles = value;
//        print("Shared:" + (_sharedFiles?.map((f) => f.path)?.join(",") ?? ""));
//      });

//      print('#### getfilePath ${value[0].path}');

      if (currentIndex == 1) {
        int nowTime = DateTime.now().millisecondsSinceEpoch;
        if (nowTime - mLastClickTime > timeInterval) {
          // do something
          if (value != null && value.length > 0) {
            MessageMgr().emit(MessageMgr.RECEIVE_THIRD_SHARE, value[0].path);
            mLastClickTime = nowTime;
          }
        } else {}
      } else {
//        print("### 记录下来了");
        if (value != null && value.length > 0) {
          tempFilePath = value[0].path;
        }
      }
    });

    // For sharing or opening urls/text coming from outside the app while the app is in the memory
        ReceiveSharingIntent.getTextStream().listen((String value) {
          print('#### getfilePath $value ');
//          setState(() {
//            _sharedText = value;
//            print("Shared: $_sharedText");
//          });
    }, onError: (err) {
      print("getLinkStream error: $err");
    });

    // For sharing or opening urls/text coming from outside the app while the app is closed
    ReceiveSharingIntent.getInitialText().then((String value) {
      print('#### getfilePath $value ');
//      setState(() {
//        _sharedText = value;
//        print("Shared: $_sharedText");
//      });
    });
  }

  static int currentIndex = 0;

  static void start() {
    currentIndex = 1;
    if (tempFilePath != null) {
      MessageMgr().emit(MessageMgr.RECEIVE_THIRD_SHARE, tempFilePath);
    }
  }

  static dispose() {
    currentIndex = 0;
  }
}
