import '../entities/beet.dart';
import '../entities/beet_row.dart';
import '../entities/plant.dart';
import '../entities/plant_in_row.dart';
import 'plant.service.dart';

class BeetRowService {
  double getTotalHorizontalSpace(final BeetRow beetRow) {
    return beetRow.plants
        .map((plant) => plant.horizontalSpace)
        .reduce((value, element) => value + element);
  }

  double getMaxVerticalSpaceOfPlantInTheRow(final BeetRow beetRow) {
    double maxVerticalSpace = 0;

    for (var plant in beetRow.plants) {
      if (plant.verticalSpace > maxVerticalSpace) {
        maxVerticalSpace = plant.verticalSpace;
      }
    }

    return maxVerticalSpace;
  }

  bool isActionNeeded(final PlantService plantService, final BeetRow beetRow,
      final DateTime date) {
    bool isActionNeeded =
        beetRow.plants.any((plant) => plantService.isActionNeeded(plant, date));

    return isActionNeeded;
  }

  List<double> getHorizontalPlantingPosition(final BeetRow beetRow) {
    double preUsedSpace = 0;
    List<double> spaceElements = [];

    for (var plant in beetRow.plants) {
      double position = preUsedSpace + (plant.horizontalSpace / 2);

      spaceElements.add(position);
      preUsedSpace += plant.horizontalSpace;
    }

    return spaceElements;
  }

  BeetRow getRowById(final Beet beet, final int rowId) {
    return beet.beetRows.firstWhere((element) => element.id == rowId);
  }

  void removePlantFromRowById(final BeetRow beetRow, final int position) {
    beetRow.plants.removeWhere((plant) => plant.position == position);
  }

  void addPlant(final BeetRow row, final Plant plant) {
    row.plants.add(_generatePlantInRow(row, plant));
  }

  PlantInRow _generatePlantInRow(final BeetRow row, final Plant plant) {
    var numberOfCurrentPlant = row.plants.length;
    return PlantInRow(position: numberOfCurrentPlant, plant: plant);
  }
}
