utils.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'package:collection/collection.dart';
  4. import 'package:flutter/material.dart';
  5. import 'package:flutter_riverpod/flutter_riverpod.dart';
  6. import 'package:intl/intl.dart';
  7. import 'package:jiffy/jiffy.dart';
  8. import 'package:path_provider/path_provider.dart';
  9. import 'package:timezone/timezone.dart' as tz;
  10. import 'package:tp5/providers/airports.dart';
  11. Jiffy jiffyfromddmmmyyhhmm(String str) => Jiffy.parse(
  12. "${str.substring(0, 7)} ${str.substring(8, 10)}:${str.substring(10, 12)}",
  13. pattern: "ddMMMyy H:mm",
  14. isUtc: true);
  15. extension JiffyExtensions on Jiffy? {
  16. Jiffy? latest(Jiffy? val2) {
  17. if (this == null) return val2;
  18. if (val2 == null) return this;
  19. if (this!.isBefore(val2)) {
  20. return val2;
  21. } else {
  22. return this;
  23. }
  24. }
  25. Jiffy? earliset(Jiffy? val2) {
  26. if (this == null) return val2;
  27. if (val2 == null) return this;
  28. if (this!.isAfter(val2)) {
  29. return val2;
  30. } else {
  31. return this;
  32. }
  33. }
  34. Jiffy max(Jiffy val2) {
  35. if (this == null) return val2;
  36. if (this!.isBefore(val2)) {
  37. return val2;
  38. } else {
  39. return this!;
  40. }
  41. }
  42. Jiffy min(Jiffy val2) {
  43. if (this == null) return val2;
  44. if (this!.isAfter(val2)) {
  45. return val2;
  46. } else {
  47. return this!;
  48. }
  49. }
  50. Jiffy setTz({String? newtz, String? ap}) =>
  51. Jiffy.parseFromDateTime(tz.TZDateTime.from(
  52. this!.dateTime,
  53. (ap != null)
  54. ? (tz.getLocation(Airports.find(ap)?.timezoneid ?? "UTC"))
  55. : (tz.getLocation(newtz ?? "UTC"))));
  56. }
  57. extension DurationLExtensions on List<Duration> {
  58. Duration get sum => fold(
  59. Duration.zero, (p, e) => Duration(minutes: p.inMinutes + e.inMinutes));
  60. }
  61. extension DurationExtensions on Duration {
  62. Duration max(Duration value) {
  63. return Duration(
  64. milliseconds: (inMilliseconds >= value.inMilliseconds)
  65. ? inMilliseconds
  66. : value.inMilliseconds);
  67. }
  68. Duration add(Duration value) {
  69. return Duration(milliseconds: inMilliseconds + value.inMilliseconds);
  70. }
  71. Duration subtract(Duration value) {
  72. return Duration(milliseconds: inMilliseconds - value.inMilliseconds);
  73. }
  74. Duration multiply(double value) {
  75. return Duration(milliseconds: (inMilliseconds * value).ceil());
  76. }
  77. // Duration intersect(Jiffy start, Jiffy end, dynamic interval) {
  78. // if (interval is List<Jiffy> && interval.length == 2) {
  79. // if ((interval[0].isSameOrBefore(start) &&
  80. // interval[1].isSameOrBefore(start)) ||
  81. // (interval[0].isSameOrAfter(end) && interval[1].isSameOrAfter(end))) {
  82. // return Duration.zero;
  83. // } else if (interval[0].isSameOrAfter(start) &&
  84. // interval[1].isSameOrBefore(end)) {
  85. // return Duration(
  86. // minutes:
  87. // interval[1].diff(interval[0], unit: Unit.minute).toInt().abs());
  88. // } else if (interval[0].isSameOrBefore(start) &&
  89. // interval[1].isSameOrAfter(end)) {
  90. // return Duration(
  91. // minutes: start.diff(end, unit: Unit.minute).toInt().abs());
  92. // } else if (interval[0].isSameOrBefore(start) &&
  93. // interval[1].isSameOrBefore(end)) {
  94. // return Duration(
  95. // minutes: start.diff(interval[1], unit: Unit.minute).toInt().abs());
  96. // } else if (interval[0].isSameOrAfter(start) &&
  97. // interval[1].isSameOrAfter(end)) {
  98. // return Duration(
  99. // minutes: interval[0].diff(end, unit: Unit.minute).toInt().abs());
  100. // } else {
  101. // return Duration.zero;
  102. // }
  103. // } else if (interval is List<List<Jiffy>>) {
  104. // return Duration(
  105. // minutes: interval.map((e) => intersect(start, end, e).inMinutes).sum);
  106. // }
  107. // throw ("Unknown type in Duration intersect: ${interval.first.runtimeType}");
  108. // // return Duration.zero;
  109. // }
  110. String get tohhmm =>
  111. "${NumberFormat("00").format(inHours)}:${NumberFormat("00").format(inMinutes % 60)}";
  112. }
  113. extension StringExtensions on String {
  114. String capitalize() {
  115. if (isEmpty) {
  116. return this;
  117. } else {
  118. return "${this[0].toUpperCase()}${substring(1).toLowerCase()}";
  119. }
  120. }
  121. String capitalizeword() {
  122. return split(' ').map((word) => word.capitalize()).join(' ');
  123. }
  124. Jiffy? parseddmmyyyyhhmm() => length >= 15
  125. ? Jiffy.parse(
  126. "${substring(6, 10)}-${substring(3, 5)}-${substring(0, 2)} ${substring(11, 13)}:${substring(13, 15)}",
  127. pattern: 'yyyy-MM-dd HH:mm',
  128. isUtc: true)
  129. : null;
  130. Jiffy? parseyyyymmddhhmm() => length >= 16
  131. ? Jiffy.parse(this,
  132. pattern: 'yyyy-MM-dd HH:mm:ss',
  133. // "${substring(6, 10)}-${substring(3, 5)}-${substring(0, 2)} ${substring(11, 13)}${substring(13, 16)}",
  134. // pattern: 'yyyy-MM-dd HH:mm',
  135. isUtc: true)
  136. : null;
  137. }
  138. extension BuildContextExt on BuildContext {
  139. ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showAlert(
  140. String message,
  141. ) =>
  142. ScaffoldMessenger.of(this).showSnackBar(
  143. SnackBar(
  144. content: Text(
  145. message,
  146. ),
  147. duration: const Duration(milliseconds: 5000),
  148. ),
  149. );
  150. ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showError(
  151. String message,
  152. ) =>
  153. ScaffoldMessenger.of(this).showSnackBar(
  154. SnackBar(
  155. backgroundColor: Colors.red,
  156. content: Text(
  157. message,
  158. style: const TextStyle(
  159. color: Colors.white, fontWeight: FontWeight.w700),
  160. ),
  161. duration: const Duration(milliseconds: 5000),
  162. ),
  163. );
  164. ScaffoldFeatureController<SnackBar, SnackBarClosedReason> showSuccess(
  165. String message,
  166. ) =>
  167. ScaffoldMessenger.of(this).showSnackBar(
  168. SnackBar(
  169. backgroundColor: Colors.green,
  170. content: Text(
  171. message,
  172. style: const TextStyle(
  173. color: Colors.white, fontWeight: FontWeight.w700),
  174. ),
  175. duration: const Duration(milliseconds: 5000),
  176. ),
  177. );
  178. Future<T?> showBottomSheet<T>({
  179. required Widget child,
  180. }) =>
  181. showModalBottomSheet<T>(
  182. context: this,
  183. builder: (_) => child,
  184. );
  185. }
  186. extension AlertDialogExt on AlertDialog {
  187. dynamic show(BuildContext context) => showDialog(
  188. context: context,
  189. builder: (BuildContext mycontext) => this,
  190. );
  191. }
  192. class ClockNotifier extends StateNotifier<Jiffy> {
  193. ClockNotifier() : super(Jiffy.now()) {
  194. timer = Timer.periodic(const Duration(minutes: 1), (timer) {
  195. state = Jiffy.now().toUtc();
  196. });
  197. }
  198. @override
  199. void dispose() {
  200. timer.cancel();
  201. super.dispose();
  202. }
  203. late final Timer timer;
  204. }
  205. final StateNotifierProvider<ClockNotifier, Jiffy> clockProvider =
  206. StateNotifierProvider<ClockNotifier, Jiffy>(
  207. (_) => ClockNotifier(),
  208. );
  209. class PathTo {
  210. static final PathTo _instance = PathTo._internal();
  211. factory PathTo() => _instance;
  212. PathTo._internal();
  213. late Directory _doc;
  214. Future<void> initialize() async {
  215. _doc = await getApplicationDocumentsDirectory();
  216. for (var dir in dirs) {
  217. if (!subd(dir).existsSync()) {
  218. subd(dir).createSync(recursive: true);
  219. }
  220. }
  221. }
  222. Directory subd(dynamic x) {
  223. if (x is String) {
  224. return Directory("${_doc.path}/$x");
  225. // } else if (x is Directory) {
  226. // return Directory("${_doc.path}/${x.path}");
  227. } else if (x is List<String>) {
  228. return subd(x.join("/"));
  229. } else {
  230. throw ("subd : x is not String nor List");
  231. }
  232. }
  233. final List<String> dirs = ["crewlink", "lido", "csv", "download"];
  234. String crewlinkFile(String file) => subd(["crewlink", file]).path;
  235. String csvFile(String file) => subd(["csv", file]).path;
  236. String lidoFile(String file) => subd(["lido", file]).path;
  237. String downloadFile(String file) => subd(["download", file]).path;
  238. }
  239. class DTInterval {
  240. late Jiffy start;
  241. late Jiffy end;
  242. DTInterval(this.start, this.end);
  243. @override
  244. String toString() =>
  245. "<${start.format(pattern: "ddMMMyy HH:mm")} - ${end.format(pattern: "ddMMMyy HH:mm")}>";
  246. //apartir has to be utc
  247. DTInterval.fromHm({
  248. required Jiffy apartir,
  249. required int h,
  250. required int m,
  251. required Duration duration,
  252. required String ap,
  253. }) {
  254. final Jiffy apartirCorrected = apartir.clone().setTz(ap: ap);
  255. Jiffy newval = Jiffy.parseFromDateTime(
  256. apartirCorrected.dateTime.copyWith(hour: h, minute: m));
  257. if (newval.isBefore(apartirCorrected)) newval = newval.add(days: 1);
  258. start = newval.toUtc();
  259. end = start.addDuration(duration).toUtc();
  260. }
  261. // DTInterval.fromHm({
  262. // required Jiffy apartir,
  263. // required int h,
  264. // required int m,
  265. // required Duration duration,
  266. // }) {
  267. // Jiffy newval = Jiffy.parseFromDateTime(
  268. // apartir.clone().dateTime.copyWith(hour: h, minute: m));
  269. // if (newval.isBefore(apartir)) newval = newval.add(days: 1);
  270. // start = newval;
  271. // end = start.addDuration(duration);
  272. // }
  273. bool include(Jiffy x) {
  274. return x.isSameOrAfter(start) && x.isSameOrBefore(end);
  275. }
  276. bool isOverlap(DTInterval x) {
  277. return x.start.isSameOrBefore(end) && x.end.isSameOrAfter(start);
  278. }
  279. bool contains(DTInterval x) {
  280. return include(x.start) && include(x.end);
  281. }
  282. DTInterval? intersection(DTInterval x) {
  283. if (!isOverlap(x)) {
  284. return null;
  285. } else {
  286. return DTInterval(start.max(x.start), end.min(x.end));
  287. }
  288. }
  289. List<DTInterval> intersectionmany(List<DTInterval> x) {
  290. return x.map((e) => intersection(e)).nonNulls.toList();
  291. }
  292. List<DTInterval> minus(DTInterval x) {
  293. if (!isOverlap(x)) {
  294. return [this];
  295. } else if (x.include(start) && x.include(end)) {
  296. return [];
  297. } else if (x.include(start)) {
  298. return [DTInterval(x.end, end)];
  299. } else if (x.include(end)) {
  300. return [DTInterval(start, x.start)];
  301. } else {
  302. return [DTInterval(start, x.start), DTInterval(x.end, end)];
  303. }
  304. }
  305. // List<DTInterval> minus(DTInterval other) {
  306. // List<DTInterval> result = [];
  307. // if (start.isBefore(other.start) && end.isAfter(other.start)) {
  308. // result.add(DTInterval(start, other.start));
  309. // }
  310. // if (start.isBefore(other.end) && end.isAfter(other.end)) {
  311. // result.add(DTInterval(other.end, end));
  312. // }
  313. // return result;
  314. // }
  315. List<DTInterval> minusmany(List<DTInterval> x) {
  316. List<DTInterval> res = [this];
  317. for (var e in x) {
  318. res = res.map((f) => f.minus(e)).flattened.toList();
  319. }
  320. return res;
  321. }
  322. Duration get duration => end.dateTime.difference(start.dateTime);
  323. // Duration get duration => Duration(
  324. // milliseconds: end.diff(start, unit: Unit.millisecond).abs().ceil());
  325. bool isEmpty() {
  326. return start.isSameOrAfter(end);
  327. }
  328. DTInterval toUtc() {
  329. return DTInterval(start.toUtc(), end.toUtc());
  330. }
  331. }