/**
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for
 * license information.
 *
 * Code generated by Microsoft (R) AutoRest Code Generator.
 */

package com.microsoft.azure.management.datamigration.v2018_03_31_preview.implementation;

import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.azure.AzureServiceFuture;
import com.microsoft.azure.ListOperationCallback;
import com.microsoft.azure.management.datamigration.v2018_03_31_preview.ApiErrorException;
import com.microsoft.azure.Page;
import com.microsoft.azure.PagedList;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponse;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.Url;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;

/**
 * An instance of this class provides access to all the operations defined
 * in Usages.
 */
public class UsagesInner {
    /** The Retrofit service to perform REST calls. */
    private UsagesService service;
    /** The service client containing this operation class. */
    private DataMigrationServiceClientImpl client;

    /**
     * Initializes an instance of UsagesInner.
     *
     * @param retrofit the Retrofit instance built from a Retrofit Builder.
     * @param client the instance of the service client containing this operation class.
     */
    public UsagesInner(Retrofit retrofit, DataMigrationServiceClientImpl client) {
        this.service = retrofit.create(UsagesService.class);
        this.client = client;
    }

    /**
     * The interface defining all the services for Usages to be
     * used by Retrofit to perform actually REST calls.
     */
    interface UsagesService {
        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.datamigration.v2018_03_31_preview.Usages list" })
        @GET("subscriptions/{subscriptionId}/providers/Microsoft.DataMigration/locations/{location}/usages")
        Observable<Response<ResponseBody>> list(@Path("subscriptionId") String subscriptionId, @Path("location") String location, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

        @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.datamigration.v2018_03_31_preview.Usages listNext" })
        @GET
        Observable<Response<ResponseBody>> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);

    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
     * @param location The Azure region of the operation
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ApiErrorException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the PagedList&lt;QuotaInner&gt; object if successful.
     */
    public PagedList<QuotaInner> list(final String location) {
        ServiceResponse<Page<QuotaInner>> response = listSinglePageAsync(location).toBlocking().single();
        return new PagedList<QuotaInner>(response.body()) {
            @Override
            public Page<QuotaInner> nextPage(String nextPageLink) {
                return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
     * @param location The Azure region of the operation
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<QuotaInner>> listAsync(final String location, final ListOperationCallback<QuotaInner> serviceCallback) {
        return AzureServiceFuture.fromPageResponse(
            listSinglePageAsync(location),
            new Func1<String, Observable<ServiceResponse<Page<QuotaInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<QuotaInner>>> call(String nextPageLink) {
                    return listNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
     * @param location The Azure region of the operation
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList&lt;QuotaInner&gt; object
     */
    public Observable<Page<QuotaInner>> listAsync(final String location) {
        return listWithServiceResponseAsync(location)
            .map(new Func1<ServiceResponse<Page<QuotaInner>>, Page<QuotaInner>>() {
                @Override
                public Page<QuotaInner> call(ServiceResponse<Page<QuotaInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
     * @param location The Azure region of the operation
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList&lt;QuotaInner&gt; object
     */
    public Observable<ServiceResponse<Page<QuotaInner>>> listWithServiceResponseAsync(final String location) {
        return listSinglePageAsync(location)
            .concatMap(new Func1<ServiceResponse<Page<QuotaInner>>, Observable<ServiceResponse<Page<QuotaInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<QuotaInner>>> call(ServiceResponse<Page<QuotaInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
    ServiceResponse<PageImpl<QuotaInner>> * @param location The Azure region of the operation
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the PagedList&lt;QuotaInner&gt; object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<QuotaInner>>> listSinglePageAsync(final String location) {
        if (this.client.subscriptionId() == null) {
            throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null.");
        }
        if (location == null) {
            throw new IllegalArgumentException("Parameter location is required and cannot be null.");
        }
        if (this.client.apiVersion() == null) {
            throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null.");
        }
        return service.list(this.client.subscriptionId(), location, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<QuotaInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<QuotaInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<QuotaInner>> result = listDelegate(response);
                        return Observable.just(new ServiceResponse<Page<QuotaInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<PageImpl<QuotaInner>> listDelegate(Response<ResponseBody> response) throws ApiErrorException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<PageImpl<QuotaInner>, ApiErrorException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<PageImpl<QuotaInner>>() { }.getType())
                .registerError(ApiErrorException.class)
                .build(response);
    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @throws ApiErrorException thrown if the request is rejected by server
     * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
     * @return the PagedList&lt;QuotaInner&gt; object if successful.
     */
    public PagedList<QuotaInner> listNext(final String nextPageLink) {
        ServiceResponse<Page<QuotaInner>> response = listNextSinglePageAsync(nextPageLink).toBlocking().single();
        return new PagedList<QuotaInner>(response.body()) {
            @Override
            public Page<QuotaInner> nextPage(String nextPageLink) {
                return listNextSinglePageAsync(nextPageLink).toBlocking().single().body();
            }
        };
    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @param serviceFuture the ServiceFuture object tracking the Retrofit calls
     * @param serviceCallback the async ServiceCallback to handle successful and failed responses.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the {@link ServiceFuture} object
     */
    public ServiceFuture<List<QuotaInner>> listNextAsync(final String nextPageLink, final ServiceFuture<List<QuotaInner>> serviceFuture, final ListOperationCallback<QuotaInner> serviceCallback) {
        return AzureServiceFuture.fromPageResponse(
            listNextSinglePageAsync(nextPageLink),
            new Func1<String, Observable<ServiceResponse<Page<QuotaInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<QuotaInner>>> call(String nextPageLink) {
                    return listNextSinglePageAsync(nextPageLink);
                }
            },
            serviceCallback);
    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList&lt;QuotaInner&gt; object
     */
    public Observable<Page<QuotaInner>> listNextAsync(final String nextPageLink) {
        return listNextWithServiceResponseAsync(nextPageLink)
            .map(new Func1<ServiceResponse<Page<QuotaInner>>, Page<QuotaInner>>() {
                @Override
                public Page<QuotaInner> call(ServiceResponse<Page<QuotaInner>> response) {
                    return response.body();
                }
            });
    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
     * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the observable to the PagedList&lt;QuotaInner&gt; object
     */
    public Observable<ServiceResponse<Page<QuotaInner>>> listNextWithServiceResponseAsync(final String nextPageLink) {
        return listNextSinglePageAsync(nextPageLink)
            .concatMap(new Func1<ServiceResponse<Page<QuotaInner>>, Observable<ServiceResponse<Page<QuotaInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<QuotaInner>>> call(ServiceResponse<Page<QuotaInner>> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink));
                }
            });
    }

    /**
     * Get resource quotas and usage information.
     * This method returns region-specific quotas and resource usage information for the Data Migration Service.
     *
    ServiceResponse<PageImpl<QuotaInner>> * @param nextPageLink The NextLink from the previous successful call to List operation.
     * @throws IllegalArgumentException thrown if parameters fail the validation
     * @return the PagedList&lt;QuotaInner&gt; object wrapped in {@link ServiceResponse} if successful.
     */
    public Observable<ServiceResponse<Page<QuotaInner>>> listNextSinglePageAsync(final String nextPageLink) {
        if (nextPageLink == null) {
            throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null.");
        }
        String nextUrl = String.format("%s", nextPageLink);
        return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Page<QuotaInner>>>>() {
                @Override
                public Observable<ServiceResponse<Page<QuotaInner>>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<PageImpl<QuotaInner>> result = listNextDelegate(response);
                        return Observable.just(new ServiceResponse<Page<QuotaInner>>(result.body(), result.response()));
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

    private ServiceResponse<PageImpl<QuotaInner>> listNextDelegate(Response<ResponseBody> response) throws ApiErrorException, IOException, IllegalArgumentException {
        return this.client.restClient().responseBuilderFactory().<PageImpl<QuotaInner>, ApiErrorException>newInstance(this.client.serializerAdapter())
                .register(200, new TypeToken<PageImpl<QuotaInner>>() { }.getType())
                .registerError(ApiErrorException.class)
                .build(response);
    }

}
