import 'dart:async';

import 'package:app/data/models/meeting_room_dto.dart';
import 'package:app/utils/time.dart';
import 'package:flutter/cupertino.dart';

class CountDownVM extends ChangeNotifier {
  MeetingRoomDto? roomInfo;

  ///会议开始倒计时秒数
  Timer? _startTime;
  int _startCountDown = 0;

  ///会议结束倒计时秒数
  Timer? _endTime;
  int _endCountDown = -1;

  ///会议进行中的秒数
  int studyTime = 0;

  int get startCountDown => _startCountDown;

  int get endCountDown => _endCountDown;

  ///是否能开始自习室
  bool get canEnterRoom {
    final now = DateTime.now();
    if (now.isAfter(parseTime(roomInfo!.startTime))) {
      return true;
    }
    return false;
  }

  //绑定
  void bind(MeetingRoomDto info) {
    if (roomInfo == info) return;
    roomInfo = info;
    _startEndCountdown();
    //如果会议室结束，停止计时器
    if (roomInfo?.roomStatus == 2) {
      _endTime?.cancel();
    }
  }

  ///启动距离会议结束还有多少秒
  void _startEndCountdown() {
    if (roomInfo!.actualStartTime.isEmpty || roomInfo!.roomStatus != 1) return;
    _endTime?.cancel();

    DateTime endTime = parseTime(roomInfo!.endTime);
    DateTime startTime = DateTime.parse(roomInfo!.actualStartTime);

    _endCountDown = endTime.difference(startTime).inSeconds;

    _endTime = Timer.periodic(Duration(seconds: 1), (timer) {
      _endCountDown--;
      studyTime++;
      if (_endCountDown <= 0) {
        _endTime?.cancel();
      }
      notifyListeners();
    });
  }

  ///启动距离会议开始还有多少秒
  void startStartCountdown() {
    if (roomInfo?.roomStatus != 0) return;
    _startTime?.cancel();
    final now = DateTime.now();
    final startTime = parseTime(roomInfo!.startTime);

    _startCountDown = startTime.difference(now).inSeconds;
    if (_startCountDown <= 0) {
      return;
    }

    _startTime = Timer.periodic(Duration(seconds: 1), (timer) {
      _startCountDown--;
      if (_startCountDown <= 0) {
        _startTime?.cancel();
        _startTime = null;
      }
      notifyListeners();
    });
  }

  @override
  void dispose() {
    _startTime?.cancel();
    _endTime?.cancel();
    super.dispose();
  }
}
