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

package com.twilio.rest.verify.v2.service.entity;

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

/**
 * PLEASE NOTE that this class contains beta products that are subject to
 * change. Use them with caution.
 */
public class ChallengeReader extends Reader<Challenge> {
    private final String pathServiceSid;
    private final String pathIdentity;
    private String factorSid;
    private Challenge.ChallengeStatuses status;
    private Challenge.ListOrders order;

    /**
     * Construct a new ChallengeReader.
     *
     * @param pathServiceSid Service Sid.
     * @param pathIdentity Unique external identifier of the Entity
     */
    public ChallengeReader(final String pathServiceSid,
                           final String pathIdentity) {
        this.pathServiceSid = pathServiceSid;
        this.pathIdentity = pathIdentity;
    }

    /**
     * The unique SID identifier of the Factor..
     *
     * @param factorSid Factor Sid.
     * @return this
     */
    public ChallengeReader setFactorSid(final String factorSid) {
        this.factorSid = factorSid;
        return this;
    }

    /**
     * The Status of the Challenges to fetch. One of `pending`, `expired`,
     * `approved` or `denied`..
     *
     * @param status The Status of theChallenges to fetch
     * @return this
     */
    public ChallengeReader setStatus(final Challenge.ChallengeStatuses status) {
        this.status = status;
        return this;
    }

    /**
     * The desired sort order of the Challenges list. One of `asc` or `desc` for
     * ascending and descending respectively. Defaults to `asc`..
     *
     * @param order The sort order of the Challenges list
     * @return this
     */
    public ChallengeReader setOrder(final Challenge.ListOrders order) {
        this.order = order;
        return this;
    }

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

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

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

        if (response == null) {
            throw new ApiConnectionException("Challenge 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(
            "challenges",
            response.getContent(),
            Challenge.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 (factorSid != null) {
            request.addQueryParam("FactorSid", factorSid);
        }

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

        if (order != null) {
            request.addQueryParam("Order", order.toString());
        }

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