Search in sources :

Example 1 with Food

use of com.faltenreich.diaguard.shared.data.database.entity.Food in project Diaguard by Faltenreich.

the class FoodDao method parseFromDto.

@Nullable
private Food parseFromDto(ProductDto dto) {
    if (dto == null || dto.identifier == null || !dto.identifier.isJsonPrimitive()) {
        return null;
    }
    String serverId = dto.identifier.getAsJsonPrimitive().getAsString();
    if (StringUtils.isBlank(serverId)) {
        return null;
    }
    Food food = getByServerId(serverId);
    boolean isNew = food == null;
    if (isNew) {
        food = new Food();
    }
    if (isNew || needsUpdate(food, dto)) {
        food.setServerId(serverId);
        food.setName(dto.name);
        food.setBrand(dto.brand);
        food.setIngredients(dto.ingredients != null ? dto.ingredients.replaceAll("_", "") : null);
        food.setLabels(dto.labels);
        food.setCarbohydrates(dto.nutrients.carbohydrates);
        food.setEnergy(dto.nutrients.energy);
        food.setFat(dto.nutrients.fat);
        food.setFatSaturated(dto.nutrients.fatSaturated);
        food.setFiber(dto.nutrients.fiber);
        food.setProteins(dto.nutrients.proteins);
        food.setSalt(dto.nutrients.salt);
        food.setSodium(dto.nutrients.sodium);
        food.setSugar(dto.nutrients.sugar);
        Locale locale = dto.languageCode != null ? new Locale(dto.languageCode) : Helper.getLocale();
        food.setLanguageCode(locale.getLanguage());
    }
    return food;
}
Also used : Locale(java.util.Locale) Food(com.faltenreich.diaguard.shared.data.database.entity.Food) Nullable(androidx.annotation.Nullable)

Example 2 with Food

use of com.faltenreich.diaguard.shared.data.database.entity.Food in project Diaguard by Faltenreich.

the class FoodDao method createOrUpdate.

public List<Food> createOrUpdate(@NonNull SearchResponseDto dto) {
    String languageCode = Helper.getLanguageCode();
    List<Food> foodList = new ArrayList<>();
    Collections.reverse(dto.products);
    for (ProductDto productDto : dto.products) {
        // Workaround: API returns products in other languages even though defined otherwise through GET parameters
        boolean isSameLanguage = languageCode.equals(productDto.languageCode);
        if (isSameLanguage && productDto.isValid()) {
            Food food = parseFromDto(productDto);
            if (food != null) {
                foodList.add(0, food);
            }
        }
    }
    FoodDao.getInstance().bulkCreateOrUpdate(foodList);
    return foodList;
}
Also used : ArrayList(java.util.ArrayList) ProductDto(com.faltenreich.diaguard.feature.food.networking.dto.ProductDto) Food(com.faltenreich.diaguard.shared.data.database.entity.Food)

Example 3 with Food

use of com.faltenreich.diaguard.shared.data.database.entity.Food in project Diaguard by Faltenreich.

the class CsvExport method doInBackground.

@Override
protected File doInBackground(Void... params) {
    DateTime dateStart = config.getDateStart();
    DateTime dateEnd = config.getDateEnd();
    Category[] categories = config.getCategories();
    boolean isBackup = config.isBackup();
    File file = isBackup ? Export.getBackupFile(config, FileType.CSV) : Export.getExportFile(config);
    try {
        FileWriter fileWriter = new FileWriter(file);
        CSVWriter writer = new CSVWriter(fileWriter, CsvMeta.CSV_DELIMITER);
        if (isBackup) {
            // Meta information to detect the data scheme in future iterations
            String[] meta = new String[] { CsvMeta.CSV_KEY_META, Integer.toString(DatabaseHelper.getVersion()) };
            writer.writeNext(meta);
            List<Tag> tags = TagDao.getInstance().getAll();
            for (Tag tag : tags) {
                writer.writeNext(ArrayUtils.add(tag.getValuesForBackup(), 0, tag.getKeyForBackup()));
            }
            List<Food> foods = FoodDao.getInstance().getAllFromUser();
            for (Food food : foods) {
                writer.writeNext(ArrayUtils.add(food.getValuesForBackup(), 0, food.getKeyForBackup()));
            }
        }
        List<Entry> entries = dateStart != null && dateEnd != null ? EntryDao.getInstance().getEntriesBetween(dateStart, dateEnd) : EntryDao.getInstance().getAll();
        int position = 0;
        for (Entry entry : entries) {
            publishProgress(String.format(Locale.getDefault(), "%s %d/%d", config.getContext().getString(R.string.entry), position, entries.size()));
            writer.writeNext(isBackup ? ArrayUtils.add(entry.getValuesForBackup(), 0, entry.getKeyForBackup()) : entry.getValuesForExport());
            List<Measurement> measurements = categories != null ? EntryDao.getInstance().getMeasurements(entry, categories) : EntryDao.getInstance().getMeasurements(entry);
            for (Measurement measurement : measurements) {
                writer.writeNext(isBackup ? ArrayUtils.add(measurement.getValuesForBackup(), 0, measurement.getKeyForBackup()) : measurement.getValuesForExport());
                if (isBackup && measurement instanceof Meal) {
                    Meal meal = (Meal) measurement;
                    for (FoodEaten foodEaten : meal.getFoodEaten()) {
                        if (foodEaten.getMeal() != null && foodEaten.getFood() != null) {
                            writer.writeNext(ArrayUtils.add(foodEaten.getValuesForBackup(), 0, foodEaten.getKeyForBackup()));
                        }
                    }
                }
            }
            if (isBackup) {
                List<EntryTag> entryTags = EntryTagDao.getInstance().getAll(entry);
                for (EntryTag entryTag : entryTags) {
                    if (entryTag.getEntry() != null && entryTag.getTag() != null) {
                        writer.writeNext(ArrayUtils.add(entryTag.getValuesForBackup(), 0, entryTag.getKeyForBackup()));
                    }
                }
            }
            position++;
        }
        writer.close();
    } catch (IOException exception) {
        Log.e(TAG, exception.toString());
    }
    return file;
}
Also used : Measurement(com.faltenreich.diaguard.shared.data.database.entity.Measurement) Category(com.faltenreich.diaguard.shared.data.database.entity.Category) FileWriter(java.io.FileWriter) Meal(com.faltenreich.diaguard.shared.data.database.entity.Meal) EntryTag(com.faltenreich.diaguard.shared.data.database.entity.EntryTag) FoodEaten(com.faltenreich.diaguard.shared.data.database.entity.FoodEaten) CSVWriter(com.opencsv.CSVWriter) IOException(java.io.IOException) DateTime(org.joda.time.DateTime) Entry(com.faltenreich.diaguard.shared.data.database.entity.Entry) Tag(com.faltenreich.diaguard.shared.data.database.entity.Tag) EntryTag(com.faltenreich.diaguard.shared.data.database.entity.EntryTag) File(java.io.File) Food(com.faltenreich.diaguard.shared.data.database.entity.Food)

Example 4 with Food

use of com.faltenreich.diaguard.shared.data.database.entity.Food in project Diaguard by Faltenreich.

the class CsvImport method importFromVersion3_0.

@SuppressWarnings("ParameterCanBeLocal")
private void importFromVersion3_0(CSVReader reader, String[] nextLine) throws Exception {
    Entry lastEntry = null;
    Meal lastMeal = null;
    while ((nextLine = reader.readNext()) != null) {
        switch(nextLine[0]) {
            case Tag.BACKUP_KEY:
                if (nextLine.length >= 2) {
                    String tagName = nextLine[1];
                    if (TagDao.getInstance().getByName(tagName) == null) {
                        Tag tag = new Tag();
                        tag.setName(nextLine[1]);
                        TagDao.getInstance().createOrUpdate(tag);
                    }
                }
                break;
            case Food.BACKUP_KEY:
                if (nextLine.length >= 5) {
                    String foodName = nextLine[1];
                    Food food = FoodDao.getInstance().get(foodName);
                    if (food == null) {
                        food = new Food();
                        food.setName(foodName);
                        food.setBrand(nextLine[2]);
                        food.setIngredients(nextLine[3]);
                        food.setCarbohydrates(FloatUtils.parseNumber(nextLine[4]));
                        FoodDao.getInstance().createOrUpdate(food);
                    } else if (food.isDeleted()) {
                        // Reactivate previously deleted food that is being re-imported
                        food.setDeletedAt(null);
                        FoodDao.getInstance().createOrUpdate(food);
                    }
                }
                break;
            case Entry.BACKUP_KEY:
                lastMeal = null;
                if (nextLine.length >= 3) {
                    DateTime parsedDateTime = DateTimeFormat.forPattern(Export.BACKUP_DATE_FORMAT).parseDateTime(nextLine[1]);
                    DateStrategy dateStrategy = this.dateStrategy != null ? this.dateStrategy : defaultDateStrategy;
                    DateTime dateTime = dateStrategy.convertDate(parsedDateTime);
                    lastEntry = new Entry();
                    lastEntry.setDate(dateTime);
                    String note = nextLine[2];
                    lastEntry.setNote(note != null && note.length() > 0 ? note : null);
                    lastEntry = EntryDao.getInstance().createOrUpdate(lastEntry);
                    break;
                }
            case Measurement.BACKUP_KEY:
                if (lastEntry != null && nextLine.length >= 3) {
                    Category category = Helper.valueOf(Category.class, nextLine[1]);
                    if (category != null) {
                        try {
                            Measurement measurement = category.toClass().newInstance();
                            List<Float> valueList = new ArrayList<>();
                            for (int position = 2; position < nextLine.length; position++) {
                                String valueString = nextLine[position];
                                try {
                                    valueList.add(FloatUtils.parseNumber(valueString));
                                } catch (NumberFormatException exception) {
                                    Log.e(TAG, exception.toString());
                                }
                            }
                            float[] values = new float[valueList.size()];
                            for (int position = 0; position < valueList.size(); position++) {
                                values[position] = valueList.get(position);
                            }
                            measurement.setValues(values);
                            measurement.setEntry(lastEntry);
                            MeasurementDao.getInstance(category.toClass()).createOrUpdate(measurement);
                            if (measurement instanceof Meal) {
                                lastMeal = (Meal) measurement;
                            }
                        } catch (InstantiationException exception) {
                            Log.e(TAG, exception.toString());
                        } catch (IllegalAccessException exception) {
                            Log.e(TAG, exception.toString());
                        }
                    }
                }
                break;
            case EntryTag.BACKUP_KEY:
                if (lastEntry != null && nextLine.length >= 2) {
                    Tag tag = TagDao.getInstance().getByName(nextLine[1]);
                    if (tag != null) {
                        EntryTag entryTag = new EntryTag();
                        entryTag.setEntry(lastEntry);
                        entryTag.setTag(tag);
                        EntryTagDao.getInstance().createOrUpdate(entryTag);
                    }
                }
                break;
            case FoodEaten.BACKUP_KEY:
                if (lastMeal != null && nextLine.length >= 3) {
                    Food food = FoodDao.getInstance().get(nextLine[1]);
                    if (food != null) {
                        FoodEaten foodEaten = new FoodEaten();
                        foodEaten.setMeal(lastMeal);
                        foodEaten.setFood(food);
                        foodEaten.setAmountInGrams(FloatUtils.parseNumber(nextLine[2]));
                        FoodEatenDao.getInstance().createOrUpdate(foodEaten);
                    }
                }
                break;
        }
    }
}
Also used : Measurement(com.faltenreich.diaguard.shared.data.database.entity.Measurement) Category(com.faltenreich.diaguard.shared.data.database.entity.Category) Meal(com.faltenreich.diaguard.shared.data.database.entity.Meal) EntryTag(com.faltenreich.diaguard.shared.data.database.entity.EntryTag) ArrayList(java.util.ArrayList) FoodEaten(com.faltenreich.diaguard.shared.data.database.entity.FoodEaten) DateStrategy(com.faltenreich.diaguard.feature.export.job.date.DateStrategy) OriginDateStrategy(com.faltenreich.diaguard.feature.export.job.date.OriginDateStrategy) DateTime(org.joda.time.DateTime) Entry(com.faltenreich.diaguard.shared.data.database.entity.Entry) Tag(com.faltenreich.diaguard.shared.data.database.entity.Tag) EntryTag(com.faltenreich.diaguard.shared.data.database.entity.EntryTag) Food(com.faltenreich.diaguard.shared.data.database.entity.Food)

Example 5 with Food

use of com.faltenreich.diaguard.shared.data.database.entity.Food in project Diaguard by Faltenreich.

the class FoodEditFragment method store.

private void store() {
    if (isValid()) {
        if (food == null) {
            food = new Food();
        }
        food.setLanguageCode(Helper.getLanguageCode());
        food.setName(getBinding().nameInput.getText());
        food.setBrand(getBinding().brandInput.getText());
        food.setIngredients(getBinding().ingredientsInput.getText());
        // FIXME: 4-digit carbohydrates are stored as 1-digit with 3 decimal places
        for (Map.Entry<Food.Nutrient, Float> entry : getBinding().nutrientInputLayout.getValues().entrySet()) {
            Food.Nutrient nutrient = entry.getKey();
            Float value = entry.getValue();
            // Auto-fill carbohydrates for user
            if (nutrient == Food.Nutrient.CARBOHYDRATES && value == null) {
                value = 0f;
            }
            nutrient.setValue(food, value != null ? value : -1);
        }
        FoodDao.getInstance().createOrUpdate(food);
        Events.post(new FoodSavedEvent(food));
        finish();
    }
}
Also used : FoodSavedEvent(com.faltenreich.diaguard.shared.event.data.FoodSavedEvent) Map(java.util.Map) Food(com.faltenreich.diaguard.shared.data.database.entity.Food)

Aggregations

Food (com.faltenreich.diaguard.shared.data.database.entity.Food)11 ArrayList (java.util.ArrayList)4 Category (com.faltenreich.diaguard.shared.data.database.entity.Category)2 Entry (com.faltenreich.diaguard.shared.data.database.entity.Entry)2 EntryTag (com.faltenreich.diaguard.shared.data.database.entity.EntryTag)2 FoodEaten (com.faltenreich.diaguard.shared.data.database.entity.FoodEaten)2 Meal (com.faltenreich.diaguard.shared.data.database.entity.Meal)2 Measurement (com.faltenreich.diaguard.shared.data.database.entity.Measurement)2 Tag (com.faltenreich.diaguard.shared.data.database.entity.Tag)2 FoodSavedEvent (com.faltenreich.diaguard.shared.event.data.FoodSavedEvent)2 IOException (java.io.IOException)2 DateTime (org.joda.time.DateTime)2 SuppressLint (android.annotation.SuppressLint)1 Nullable (androidx.annotation.Nullable)1 AppCompatButton (androidx.appcompat.widget.AppCompatButton)1 DateStrategy (com.faltenreich.diaguard.feature.export.job.date.DateStrategy)1 OriginDateStrategy (com.faltenreich.diaguard.feature.export.job.date.OriginDateStrategy)1 ProductDto (com.faltenreich.diaguard.feature.food.networking.dto.ProductDto)1 SelectArg (com.j256.ormlite.stmt.SelectArg)1 CSVReader (com.opencsv.CSVReader)1