
import 'package:guru_utils/datetime/datetime_utils.dart';

/// Created by Haoyi on 2020/8/29
///

enum RangeType {
  INCLUSIVE_INCLUSIVE, // [begin, end]
  INCLUSIVE_EXCLUSIVE, // [begin, end)
  EXCLUSIVE_INCLUSIVE, // (begin, end]
  EXCLUSIVE_EXCLUSIVE // (begin, end)
}

class Range<T> {
  final num begin;
  final num end;
  final T? data;

  const Range(this.begin, this.end, {this.data});

  Range.sinceNow(Duration duration, {this.data})
      : begin = DateTimeUtils.currentTimeInSecond(),
        end = DateTimeUtils.currentTimeInSecond() + duration.inSeconds;

  static Range? fromString(String text) {
    if (text.isNotEmpty != true) {
      return null;
    }
    final values = text.split(":");
    try {
      if (values.length >= 2) {
        return Range(int.parse(values[0]), int.parse(values[1]));
      }
    } catch (error) {}
    return null;
  }

  bool inRange(num value, {RangeType type = RangeType.INCLUSIVE_INCLUSIVE}) {
    switch (type) {
      case RangeType.INCLUSIVE_INCLUSIVE:
        return value >= begin && value <= end;
      case RangeType.INCLUSIVE_EXCLUSIVE:
        return value >= begin && value < end;
      case RangeType.EXCLUSIVE_INCLUSIVE:
        return value > begin && value <= end;
      default:
        return value > begin && value < end;
    }
  }

  @override
  String toString() {
    return "$begin:$end";
  }

  num get interval => end - begin;
}
