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

package com.twilio.rest.verify.v2;

import com.twilio.base.Page;
import com.twilio.base.Reader;
import com.twilio.base.ResourceSet;
import com.twilio.converter.DateConverter;
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;

public class VerificationAttemptReader extends Reader<VerificationAttempt> {
    private ZonedDateTime dateCreatedAfter;
    private ZonedDateTime dateCreatedBefore;
    private String channelDataTo;
    private String country;
    private VerificationAttempt.Channels channel;
    private String verifyServiceSid;
    private String verificationSid;
    private VerificationAttempt.ConversionStatus status;

    /**
     * Datetime filter used to query Verification Attempts created after this
     * datetime. Given as GMT in RFC 2822 format..
     *
     * @param dateCreatedAfter Filter verification attempts after this date.
     * @return this
     */
    public VerificationAttemptReader setDateCreatedAfter(final ZonedDateTime dateCreatedAfter) {
        this.dateCreatedAfter = dateCreatedAfter;
        return this;
    }

    /**
     * Datetime filter used to query Verification Attempts created before this
     * datetime. Given as GMT in RFC 2822 format..
     *
     * @param dateCreatedBefore Filter verification attempts before this date.
     * @return this
     */
    public VerificationAttemptReader setDateCreatedBefore(final ZonedDateTime dateCreatedBefore) {
        this.dateCreatedBefore = dateCreatedBefore;
        return this;
    }

    /**
     * Destination of a verification. It is phone number in E.164 format..
     *
     * @param channelDataTo Filters by destination of the verification attempt.
     * @return this
     */
    public VerificationAttemptReader setChannelDataTo(final String channelDataTo) {
        this.channelDataTo = channelDataTo;
        return this;
    }

    /**
     * Filter used to query Verification Attempts sent to the specified destination
     * country..
     *
     * @param country Filter verification attempts by destination country.
     * @return this
     */
    public VerificationAttemptReader setCountry(final String country) {
        this.country = country;
        return this;
    }

    /**
     * Filter used to query Verification Attempts by communication channel. Valid
     * values are `SMS` and `CALL`.
     *
     * @param channel Filter verification attempts by communication channel.
     * @return this
     */
    public VerificationAttemptReader setChannel(final VerificationAttempt.Channels channel) {
        this.channel = channel;
        return this;
    }

    /**
     * Filter used to query Verification Attempts by verify service. Only attempts
     * of the provided SID will be returned..
     *
     * @param verifyServiceSid Filter verification attempts by verify service.
     * @return this
     */
    public VerificationAttemptReader setVerifyServiceSid(final String verifyServiceSid) {
        this.verifyServiceSid = verifyServiceSid;
        return this;
    }

    /**
     * Filter used to return all the Verification Attempts of a single verification.
     * Only attempts of the provided verification SID will be returned..
     *
     * @param verificationSid Filter attempts by verification.
     * @return this
     */
    public VerificationAttemptReader setVerificationSid(final String verificationSid) {
        this.verificationSid = verificationSid;
        return this;
    }

    /**
     * Filter used to query Verification Attempts by conversion status. Valid values
     * are `UNCONVERTED`, for attempts that were not converted, and `CONVERTED`, for
     * attempts that were confirmed..
     *
     * @param status Filter verification attempts by conversion status.
     * @return this
     */
    public VerificationAttemptReader setStatus(final VerificationAttempt.ConversionStatus status) {
        this.status = status;
        return this;
    }

    /**
     * Make the request to the Twilio API to perform the read.
     *
     * @param client TwilioRestClient with which to make the request
     * @return VerificationAttempt ResourceSet
     */
    @Override
    public ResourceSet<VerificationAttempt> 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 VerificationAttempt ResourceSet
     */
    @Override
    @SuppressWarnings("checkstyle:linelength")
    public Page<VerificationAttempt> firstPage(final TwilioRestClient client) {
        Request request = new Request(
            HttpMethod.GET,
            Domains.VERIFY.toString(),
            "/v2/Attempts"
        );

        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 VerificationAttempt ResourceSet
     */
    @Override
    @SuppressWarnings("checkstyle:linelength")
    public Page<VerificationAttempt> getPage(final String targetUrl, final TwilioRestClient client) {
        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<VerificationAttempt> nextPage(final Page<VerificationAttempt> page,
                                              final TwilioRestClient client) {
        Request request = new Request(
            HttpMethod.GET,
            page.getNextPageUrl(Domains.VERIFY.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<VerificationAttempt> previousPage(final Page<VerificationAttempt> page,
                                                  final TwilioRestClient client) {
        Request request = new Request(
            HttpMethod.GET,
            page.getPreviousPageUrl(Domains.VERIFY.toString())
        );
        return pageForRequest(client, request);
    }

    /**
     * Generate a Page of VerificationAttempt 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<VerificationAttempt> pageForRequest(final TwilioRestClient client, final Request request) {
        Response response = client.request(request);

        if (response == null) {
            throw new ApiConnectionException("VerificationAttempt 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(
            "attempts",
            response.getContent(),
            VerificationAttempt.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 (dateCreatedAfter != null) {
            request.addQueryParam("DateCreatedAfter", dateCreatedAfter.toInstant().toString());
        }

        if (dateCreatedBefore != null) {
            request.addQueryParam("DateCreatedBefore", dateCreatedBefore.toInstant().toString());
        }

        if (channelDataTo != null) {
            request.addQueryParam("ChannelData.To", channelDataTo);
        }

        if (country != null) {
            request.addQueryParam("Country", country);
        }

        if (channel != null) {
            request.addQueryParam("Channel", channel.toString());
        }

        if (verifyServiceSid != null) {
            request.addQueryParam("VerifyServiceSid", verifyServiceSid);
        }

        if (verificationSid != null) {
            request.addQueryParam("VerificationSid", verificationSid);
        }

        if (status != null) {
            request.addQueryParam("Status", status.toString());
        }

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