package io.ljunggren.sendgrid.api.service;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Collections;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.sendgrid.Method;
import com.sendgrid.Request;
import com.sendgrid.Response;
import com.sendgrid.SendGrid;

import io.ljunggren.json.utils.JsonUtils;
import io.ljunggren.sendgrid.api.exception.SendgridException;
import io.ljunggren.sendgrid.api.model.Statistics;

/**
 * Service that retrieves email-sending statistics from the
 * SendGrid {@code /stats} endpoint.
 */
public class UsageService extends BaseService {

	private static final String STATS_ENDPOINT = "stats";
	private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().registerModule(new JavaTimeModule());

	/**
	 * Create a new {@code UsageService} backed by a real SendGrid client.
	 *
	 * @param apiKey the SendGrid API key
	 * @throws IllegalArgumentException if {@code apiKey} is null or blank
	 */
	public UsageService(String apiKey) {
		super(apiKey);
	}

	/**
	 * Test-only constructor that accepts a pre-built (possibly mocked) client.
	 *
	 * @param sendGrid the SendGrid client to use
	 */
	UsageService(SendGrid sendGrid) {
		super(sendGrid);
	}

	/**
	 * Returns statistics for today only.
	 *
	 * @return a non-null list of {@link Statistics} (one entry for today)
	 * @throws SendgridException if the call fails
	 */
	public List<Statistics> getDailyUsage() throws SendgridException {
		return getStatistics(0);
	}

	/**
	 * Returns statistics for the current calendar month so far,
	 * day-by-day, from the first of the month through today.
	 *
	 * @return a non-null list of {@link Statistics}
	 * @throws SendgridException if the call fails
	 */
	public List<Statistics> getMonthlyStatistics() throws SendgridException {
		int dayOfMonth = LocalDate.now().getDayOfMonth();
		return getStatistics(dayOfMonth - 1);
	}

	/**
	 * Returns daily statistics for the last {@code days} days through today.
	 *
	 * @param days how many days back from today (inclusive of today)
	 * @return a non-null list of {@link Statistics}
	 * @throws SendgridException        if the call fails
	 * @throws IllegalArgumentException if {@code days} is negative
	 */
	public List<Statistics> getStatistics(int days) throws SendgridException {
		return getStatistics(days, Aggregation.DAY);
	}

	/**
	 * Returns statistics for the last {@code days} days, aggregated by
	 * the given granularity.
	 *
	 * @param days        how many days back from today (inclusive of today)
	 * @param aggregation aggregation granularity
	 * @return a non-null list of {@link Statistics}
	 * @throws SendgridException        if the call fails
	 * @throws IllegalArgumentException if {@code days} is negative or {@code aggregation} is null
	 */
	public List<Statistics> getStatistics(int days, Aggregation aggregation) throws SendgridException {
		if (days < 0) {
			throw new IllegalArgumentException("days must not be negative");
		}
		if (aggregation == null) {
			throw new IllegalArgumentException("aggregation must not be null");
		}
		LocalDate endDate = LocalDate.now();
		LocalDate startDate = endDate.minusDays(days);
		return getStatistics(aggregation.getValue(),
				startDate.format(DATE_FORMATTER),
				endDate.format(DATE_FORMATTER));
	}

	private List<Statistics> getStatistics(String aggregate, String startDate, String endDate) throws SendgridException {
		Request request = new Request();
		request.setMethod(Method.GET);
		request.setEndpoint(STATS_ENDPOINT);
		request.addQueryParam("aggregated_by", aggregate);
		request.addQueryParam("start_date", startDate);
		request.addQueryParam("end_date", endDate);
		Response response;
		try {
			response = sendGrid.api(request);
		} catch (IOException e) {
			throw new SendgridException("Failed to call SendGrid stats endpoint", e);
		}
		if (response == null) {
			throw new SendgridException("SendGrid stats endpoint returned no response");
		}
		if (response.getStatusCode() < HttpURLConnection.HTTP_OK
				|| response.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
			throw new SendgridException("SendGrid stats endpoint returned status="
					+ response.getStatusCode() + ", body=" + response.getBody());
		}
		try {
			List<Statistics> statistics = JsonUtils.jsonToList(response.getBody(), Statistics.class, OBJECT_MAPPER);
			return statistics == null ? Collections.emptyList() : statistics;
		} catch (Exception e) {
			throw new SendgridException("Failed to parse SendGrid stats response", e);
		}
	}

}
