diff --git a/src/main/java/core/basesyntax/InvalidDataException.java b/src/main/java/core/basesyntax/InvalidDataException.java new file mode 100644 index 000000000..d2c862295 --- /dev/null +++ b/src/main/java/core/basesyntax/InvalidDataException.java @@ -0,0 +1,7 @@ +package core.basesyntax; + +public class InvalidDataException extends RuntimeException { + public InvalidDataException(String message) { + super(message); + } +} diff --git a/src/main/java/core/basesyntax/SalaryInfo.java b/src/main/java/core/basesyntax/SalaryInfo.java index 4a34339b5..7bad94a05 100644 --- a/src/main/java/core/basesyntax/SalaryInfo.java +++ b/src/main/java/core/basesyntax/SalaryInfo.java @@ -1,7 +1,56 @@ package core.basesyntax; +import java.time.LocalDate; +import java.time.format.DateTimeFormatter; + public class SalaryInfo { + + private static final DateTimeFormatter DATES = DateTimeFormatter.ofPattern("dd.MM.yyyy"); + + public LocalDate parseDate(String date) { + try { + return LocalDate.parse(date, DATES); + } catch (Exception e) { + throw new InvalidDataException( + "Invalid date format. Only dd.MM.yyyy format is accepted" + ); + } + } + public String getSalaryInfo(String[] names, String[] data, String dateFrom, String dateTo) { - return null; + if (names == null || data == null || dateFrom == null || dateTo == null) { + throw new InvalidDataException("Invalid data: Please check your input"); + } + + LocalDate dateFromFormatted = parseDate(dateFrom); + LocalDate dateToFormatted = parseDate(dateTo); + + StringBuilder output = new StringBuilder("Report for period " + + DATES.format(dateFromFormatted) + + " - " + + DATES.format(dateToFormatted)); + + for (String name : names) { + int salary = 0; + for (String part : data) { + String[] dataPart = part.split(" "); + LocalDate datePart = LocalDate.parse(dataPart[0], DATES); + + if (dataPart[1].equals(name) + && !datePart.isBefore(dateFromFormatted) + && !datePart.isAfter((dateToFormatted))) { + salary += Integer.parseInt(dataPart[2]) * Integer.parseInt(dataPart[3]); + } + } + + output.append(System.lineSeparator()) + .append(name) + .append(" - ") + .append(salary); + + } + + return output.toString(); } + }