package ru.yandex.webmaster3.viewer.util;

import org.jetbrains.annotations.Nullable;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import ru.yandex.webmaster3.core.util.TimeUtils;
import ru.yandex.webmaster3.proto.dashboard.cache.DashboardCache;
import ru.yandex.webmaster3.core.link.DatePoint;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author aherman
 */
public class DashboardUtils {
    public static int localDateToInt(@Nullable LocalDate localDate) {
        if (localDate == null) {
            return 0;
        } else {
            return TimeUtils.toUnixTimestamp(localDate.toDateTimeAtStartOfDay(TimeUtils.EUROPE_MOSCOW_ZONE));
        }
    }

    public static LocalDate intToLocalDate(int value) {
        return intToLocalDateTime(value).toLocalDate();
    }

    public static LocalDateTime intToLocalDateTime(int value) {
        return TimeUtils.unixTimestampToDate(value, TimeUtils.EUROPE_MOSCOW_ZONE).toLocalDateTime();
    }

    public static List<DashboardCache.DatePoint> datePointsToProto(List<DatePoint> points) {
        return points.stream()
                .map(point -> DashboardCache.DatePoint.newBuilder()
                        .setTime(localDateToInt(point.getTime()))
                        .setValue(point.getValue())
                        .build()
                ).collect(Collectors.toList());
    }

    public static List<DatePoint> datePointsFromProto(List<DashboardCache.DatePoint> points) {
        return points.stream()
                .map(point -> new DatePoint(intToLocalDate(point.getTime()), point.getValue()))
                .collect(Collectors.toList());
    }
}
