import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:hl_lieferservice/model/tour.dart';
import 'package:path_provider/path_provider.dart';

class ReorderService {
  get _path async {
    final dir = await getApplicationDocumentsDirectory();
    final date = DateTime.now();
    final filename = "custom_sort_${date.year}_${date.month}_${date.day}.json";
    final path = "${dir.path}/$filename";

    return path;
  }

  Future<File> get _file async {
    final path = await _path;
    final file = File(path);

    return file;
  }

  Future<void> saveSortingInformation(
    Map<String, List<String>> container,
  ) async {
    debugPrint("CONTAINER: ${jsonEncode(container)}");

    (await _file).writeAsString(jsonEncode(container));
  }

  Future<void> initializeTour(Tour tour) async {
    (await _file).create();
    Map<String, List<String>> sorting = {};

    for (final delivery in tour.deliveries) {
      if (!sorting.containsKey(delivery.carId.toString())) {
        sorting[delivery.carId.toString()] = [delivery.id];
      } else {
        sorting[delivery.carId.toString()]!.add(delivery.id);
      }
    }

    (await _file).writeAsString(jsonEncode({"cars": sorting}));
  }

  bool orderInformationExist() {
    return false;
  }

  Future<Map<String, List<String>>> loadSortingInformation() async {
    debugPrint("FILE: ${await (await _file).readAsString()}");
    Map<String, List<String>> container = {};
    Map<String, dynamic> json = jsonDecode(await (await _file).readAsString());

    if (!json.containsKey("cars")) {
      throw Exception("No cars found in file");
    }

    for (final car in json["cars"].entries) {
      List<String> values = [];

      for (String value in car.value) {
        values.add(value);
      }

      container[car.key] = values;
    }


    return container;
  }
}
