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

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

import '../model/sorting_information.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(SortingInformationContainer container) async {
    (await _file).writeAsString(jsonEncode(container.toJson()));
  }

  Future<void> initializeTour(Tour tour) async {
    (await _file).create();
    SortingInformationContainer container = SortingInformationContainer(sorting: []);
    
    for (final (index, delivery) in tour.deliveries.indexed) {
      container.sorting.add(
        SortingInformation(deliveryId: delivery.id, position: index),
      );
    }

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

  bool orderInformationExist() {
    return false;
  }

  Future<SortingInformationContainer> loadSortingInformation() async {
    return SortingInformationContainer.fromJson(
        jsonDecode(await (await _file).readAsString()),
    );
  }
}