/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */

package com.twilio.rest.api.v2010.account;

import com.twilio.base.Page;
import com.twilio.base.Reader;
import com.twilio.base.ResourceSet;
import com.twilio.converter.DateConverter;
import com.twilio.converter.Promoter;
import com.twilio.exception.ApiConnectionException;
import com.twilio.exception.ApiException;
import com.twilio.exception.RestException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;

import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class MessageReader extends Reader<Message> {
    private String pathAccountSid;
    private com.twilio.type.PhoneNumber to;
    private com.twilio.type.PhoneNumber from;
    private ZonedDateTime dateSent;
    private ZonedDateTime dateSentBefore;
    private ZonedDateTime dateSentAfter;

    /**
     * Construct a new MessageReader.
     */
    public MessageReader() {
    }

    /**
     * Construct a new MessageReader.
     *
     * @param pathAccountSid The SID of the Account that created the resources to
     *                       read
     */
    public MessageReader(final String pathAccountSid) {
        this.pathAccountSid = pathAccountSid;
    }

    /**
     * Read messages sent to only this phone number..
     *
     * @param to Filter by messages sent to this number
     * @return this
     */
    public MessageReader setTo(final com.twilio.type.PhoneNumber to) {
        this.to = to;
        return this;
    }

    /**
     * Read messages sent to only this phone number..
     *
     * @param to Filter by messages sent to this number
     * @return this
     */
    public MessageReader setTo(final String to) {
        return setTo(Promoter.phoneNumberFromString(to));
    }

    /**
     * Read messages sent from only this phone number or alphanumeric sender ID..
     *
     * @param from Filter by from number
     * @return this
     */
    public MessageReader setFrom(final com.twilio.type.PhoneNumber from) {
        this.from = from;
        return this;
    }

    /**
     * Read messages sent from only this phone number or alphanumeric sender ID..
     *
     * @param from Filter by from number
     * @return this
     */
    public MessageReader setFrom(final String from) {
        return setFrom(Promoter.phoneNumberFromString(from));
    }

    /**
     * The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to
     * read only messages sent on this date. For example: `2009-07-06`. You can also
     * specify an inequality, such as `DateSent&lt;=YYYY-MM-DD`, to read messages
     * sent on or before midnight on a date, and `DateSent&gt;=YYYY-MM-DD` to read
     * messages sent on or after midnight on a date..
     *
     * @param dateSent Filter by date sent
     * @return this
     */
    public MessageReader setDateSent(final ZonedDateTime dateSent) {
        this.dateSentBefore = null;
        this.dateSentAfter = null;
        this.dateSent = dateSent;
        return this;
    }

    /**
     * The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to
     * read only messages sent on this date. For example: `2009-07-06`. You can also
     * specify an inequality, such as `DateSent&lt;=YYYY-MM-DD`, to read messages
     * sent on or before midnight on a date, and `DateSent&gt;=YYYY-MM-DD` to read
     * messages sent on or after midnight on a date..
     *
     * @param dateSentBefore Filter by date sent
     * @return this
     */
    public MessageReader setDateSentBefore(final ZonedDateTime dateSentBefore) {
        this.dateSent = null;
        this.dateSentBefore = dateSentBefore;
        return this;
    }

    /**
     * The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to
     * read only messages sent on this date. For example: `2009-07-06`. You can also
     * specify an inequality, such as `DateSent&lt;=YYYY-MM-DD`, to read messages
     * sent on or before midnight on a date, and `DateSent&gt;=YYYY-MM-DD` to read
     * messages sent on or after midnight on a date..
     *
     * @param dateSentAfter Filter by date sent
     * @return this
     */
    public MessageReader setDateSentAfter(final ZonedDateTime dateSentAfter) {
        this.dateSent = null;
        this.dateSentAfter = dateSentAfter;
        return this;
    }

    /**
     * Make the request to the Twilio API to perform the read.
     *
     * @param client TwilioRestClient with which to make the request
     * @return Message ResourceSet
     */
    @Override
    public ResourceSet<Message> read(final TwilioRestClient client) {
        return new ResourceSet<>(this, client, firstPage(client));
    }

    /**
     * Make the request to the Twilio API to perform the read.
     *
     * @param client TwilioRestClient with which to make the request
     * @return Message ResourceSet
     */
    @Override
    @SuppressWarnings("checkstyle:linelength")
    public Page<Message> firstPage(final TwilioRestClient client) {
        this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid;
        Request request = new Request(
            HttpMethod.GET,
            Domains.API.toString(),
            "/2010-04-01/Accounts/" + this.pathAccountSid + "/Messages.json"
        );

        addQueryParams(request);
        return pageForRequest(client, request);
    }

    /**
     * Retrieve the target page from the Twilio API.
     *
     * @param targetUrl API-generated URL for the requested results page
     * @param client TwilioRestClient with which to make the request
     * @return Message ResourceSet
     */
    @Override
    @SuppressWarnings("checkstyle:linelength")
    public Page<Message> getPage(final String targetUrl, final TwilioRestClient client) {
        this.pathAccountSid = this.pathAccountSid == null ? client.getAccountSid() : this.pathAccountSid;
        Request request = new Request(
            HttpMethod.GET,
            targetUrl
        );

        return pageForRequest(client, request);
    }

    /**
     * Retrieve the next page from the Twilio API.
     *
     * @param page current page
     * @param client TwilioRestClient with which to make the request
     * @return Next Page
     */
    @Override
    public Page<Message> nextPage(final Page<Message> page,
                                  final TwilioRestClient client) {
        Request request = new Request(
            HttpMethod.GET,
            page.getNextPageUrl(Domains.API.toString())
        );
        return pageForRequest(client, request);
    }

    /**
     * Retrieve the previous page from the Twilio API.
     *
     * @param page current page
     * @param client TwilioRestClient with which to make the request
     * @return Previous Page
     */
    @Override
    public Page<Message> previousPage(final Page<Message> page,
                                      final TwilioRestClient client) {
        Request request = new Request(
            HttpMethod.GET,
            page.getPreviousPageUrl(Domains.API.toString())
        );
        return pageForRequest(client, request);
    }

    /**
     * Generate a Page of Message Resources for a given request.
     *
     * @param client TwilioRestClient with which to make the request
     * @param request Request to generate a page for
     * @return Page for the Request
     */
    private Page<Message> pageForRequest(final TwilioRestClient client, final Request request) {
        Response response = client.request(request);

        if (response == null) {
            throw new ApiConnectionException("Message read failed: Unable to connect to server");
        } else if (!TwilioRestClient.SUCCESS.test(response.getStatusCode())) {
            RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper());
            if (restException == null) {
                throw new ApiException("Server Error, no content");
            }
           throw new ApiException(restException);
        }

        return Page.fromJson(
            "messages",
            response.getContent(),
            Message.class,
            client.getObjectMapper()
        );
    }

    /**
     * Add the requested query string arguments to the Request.
     *
     * @param request Request to add query string arguments to
     */
    private void addQueryParams(final Request request) {
        if (to != null) {
            request.addQueryParam("To", to.toString());
        }

        if (from != null) {
            request.addQueryParam("From", from.toString());
        }

        if (dateSent != null) {
            request.addQueryParam("DateSent", dateSent.format(DateTimeFormatter.ofPattern(Request.QUERY_STRING_DATE_TIME_FORMAT)));
        } else if (dateSentAfter != null || dateSentBefore != null) {
            request.addQueryDateTimeRange("DateSent", dateSentAfter, dateSentBefore);
        }

        if (getPageSize() != null) {
            request.addQueryParam("PageSize", Integer.toString(getPageSize()));
        }
    }
}