1
0

utils.dart 11 KB

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