/*
 * (C) Copyright 2017 Kyle F. Downey.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cloudwall.exchange.coinbase;

import cloudwall.exchange.AccountManagementService;
import cloudwall.exchange.ExchangeLogin;
import cloudwall.exchange.ExchangeProductLoader;
import cloudwall.exchange.PropertiesCredentialStore;
import cloudwall.infra.reactive.RealtimeSchedulingTimeline;
import cloudwall.infra.reactive.Timeline;
import cloudwall.infra.scheduler.ScheduledExectorServiceScheduler;
import cloudwall.infra.scheduler.Scheduler;
import cloudwall.infra.webservice.ApiSession;
import cloudwall.order.OrderGateway;
import cloudwall.product.CryptoProductLoader;
import cloudwall.product.LoadableProductMaster;
import cloudwall.product.ProductMaster;
import com.ifesdjeen.timer.HashedWheelTimer;
import dagger.Module;
import dagger.Provides;

import javax.inject.Singleton;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ScheduledExecutorService;

/**
 * Injectable elements for applications that need GDAX connectivity.
 *
 * @author <a href="mailto:kyle.downey@gmail.com">Kyle F. Downey</a>
 */
@Module
public class CoinbaseServiceModule {
    @Provides
    public Scheduler provideScheduler() {
        ScheduledExecutorService timer = new HashedWheelTimer();
        return new ScheduledExectorServiceScheduler(timer);
    }

    @Provides
    @Singleton
    public Timeline provideTimeline(Scheduler scheduler) {
        return new RealtimeSchedulingTimeline(scheduler);
    }

    @Provides
    public ProductMaster provideProductMaster(ExchangeProductLoader productLoader) {
        LoadableProductMaster productMaster = new LoadableProductMaster();
        productMaster.addProducts(new CryptoProductLoader());
        productMaster.addProducts(productLoader);
        return productMaster;
    }

    @Provides
    public ExchangeProductLoader provideExchangeProductLoader(CoinbaseExchangeSession session) {
        return new CoinbaseExchangeProductLoader(new ApiSession(session));
    }

    @Provides
    @Singleton
    public CoinbaseExchangeSession provideExchangeSession() {
        PropertiesCredentialStore credentialStore = new PropertiesCredentialStore("gdax",
                CoinbaseExchangeCredentials::new);

        ExchangeLogin credentials;
        try {
            credentials = credentialStore.loadCredentials();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        CoinbaseExchangeConnection connection = new CoinbaseExchangeConnection("api.pro.coinbase.com", "ws-feed.pro.coinbase.com", 443);
        return (CoinbaseExchangeSession) connection.openSession(credentials);
    }

    @Provides
    @Singleton
    public CompletableFuture<CoinbaseMarketdataClient> provideMarketdataClient(Timeline timeline,
                                                                               ProductMaster productMaster,
                                                                               CoinbaseExchangeSession session) {
        return productMaster.getProductSet().thenApply(products ->
                new CoinbaseMarketdataClient(timeline, session, products));
    }

    @Provides
    public AccountManagementService provideAccountManager(CoinbaseExchangeSession session) {
        return new CoinbaseAccountManagementService(new ApiSession(session));
    }

    @Provides
    public CompletableFuture<CoinbaseOrderManager> provideOrderManager(Timeline timeline,
                                                                       CompletableFuture<CoinbaseMarketdataClient> mdClientFuture) {
        return mdClientFuture.thenApply(mdClient -> new CoinbaseOrderManager(timeline, mdClient));
    }

    @Provides
    public CompletableFuture<OrderGateway> provideOrderGateway(CoinbaseExchangeSession session,
                                                               CompletableFuture<CoinbaseOrderManager> omFuture,
                                                               ProductMaster productMaster) {
        CompletableFuture<Void> depsReady = CompletableFuture.allOf(omFuture, productMaster.getProductSet());
        return depsReady.thenApply(ready ->
            new CoinbaseOrderGateway(session,
                    omFuture.getNow(null),
                    productMaster.getProductSet().getNow(null))
        );
    }
}
