aboutsummaryrefslogtreecommitdiff
path: root/lib/models/data/recipe_data_class.dart
blob: 78fe791542d838921b6cd5ff98a88671764fcb4f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import 'dart:convert';

import 'package:kulinar_app/models/recipe_class.dart';
import 'package:kulinar_app/util/isar_handler.dart';

class RecipeData {
  static List<Recipe> remoteRecipeList = [];
  static List<Recipe> recipeList = [];

  static Future<void> save() async {
    IsarHandler isar = IsarHandler();

    await isar.clear();

    for (Recipe recipe in recipeList) {
      isar.save(recipe);
    }
  }

  static Future<void> load() async {
    List<Recipe?> list = await IsarHandler().load();

    for (Recipe? recipe in list) {
      recipeList.add(recipe!);
    }
  }

  static String encode() {
    List<Map<String, dynamic>> tempList = [];

    for (Recipe recipe in recipeList) {
      Map<String, dynamic> map = {};

      map["title"] = recipe.title;
      map["description"] = recipe.description;
      map["favorite"] = recipe.favorite;
      map["rating"] = recipe.rating;
      map["image"] = recipe.image;

      tempList.add(map);
    }

    return jsonEncode(tempList);
  }

  static void decode(String data) {
    final result = jsonDecode(data);

    if (result.isEmpty) return;

    recipesIdentical(Recipe a, Recipe b) {
      if (a.title != b.title) return false;
      if (a.description != b.description) return false;

      return true;
    }

    result.forEach((item) {
      Recipe recipe = Recipe(
        title: item["title"],
        description: item["description"],
        favorite: item["favorite"],
        rating: item["rating"],
        image: item["image"],
      );

      if (RecipeData.recipeList.where((element) => recipesIdentical(element, recipe)).isEmpty) recipeList.add(recipe);
    });

    save();
  }
}