import { create } from 'axios';
import { Observable } from '@reactivex/rxjs';

import Contract from './contract';

const TRANSACTION_RECEIPT_POLL_MS = 2000;

const ETH_CLIENT = Symbol();

function getTransactionReceipt(ethClient, txHash) {
    return ethClient.send('eth_getTransactionReceipt', [ txHash ]);
}

function pollForTransactionReceipt(ethClient, txHash) {
    return new Promise((resolve, reject) => {
        const pollIntervalId = setInterval(
            () => {
                getTransactionReceipt(ethClient, txHash)
                    .then(
                        res => {
                            if (res.result) {
                                clearInterval(pollIntervalId);
                                resolve(res.result);
                            }
                        },
                        err => reject(err)
                    )
        }, TRANSACTION_RECEIPT_POLL_MS);
    });
}

export default class Contracts {
    constructor(ethClient) {
        this[ETH_CLIENT] = ethClient;
    }

    create(abi, params) {
        // return new Contract(this[ETH_CLIENT], abi);
        return Observable.create(observer => {
            const ethClient = this[ETH_CLIENT];
            ethClient
                .send('eth_sendTransaction', [ params ])
                .then(
                    res => {
                        const txHash = res.result;
                        observer.next({
                            txHash,
                        });
                        pollForTransactionReceipt(ethClient, txHash)
                            .then(
                                res => {
                                    observer.next(res);
                                    observer.complete();
                                },
                                err => observer.error(err)
                            );
                    },
                    err => observer.error(err)
                );
        });
    }
}

@@ -418,68 +418,58 @@
     
-cons
+le
 t poll
-IntervalId = setInterval(%0A            () =%3E %7B%0A    
+TimeoutId;%0A        const pollFunc = () =%3E%0A
     
@@ -664,29 +664,27 @@
 lear
-Interval(pollInterval
+Timeout(pollTimeout
 Id);
@@ -737,16 +737,214 @@
 esult);%0A
+                            %7D else %7B%0A                                clearTimeout(pollTimeoutId);%0A                                pollTimeoutId  = setTimeout(pollFunc, TRANSACTION_RECEIPT_POLL_MS);%0A
         
@@ -1056,16 +1056,18 @@
        )
+;%0A
 %0A       
@@ -1071,38 +1071,17 @@
     
-%7D, TRANSACTION_RECEIPT_POLL_MS
+pollFunc(
 );%0A 

improve transaction polling