"use strict";
// Copyright 2017-2020 @polkadot/rpc-provider authors & contributors
// This software may be modified and distributed under the terms
// of the Apache-2.0 license. See the LICENSE file for details.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
require("./polyfill");
const util_1 = require("@polkadot/util");
const coder_1 = __importDefault(require("../coder"));
const defaults_1 = __importDefault(require("../defaults"));
const ERROR_SUBSCRIBE = 'HTTP Provider does not have subscriptions, use WebSockets instead';
const l = util_1.logger('api-http');
/**
 * # @polkadot/rpc-provider/https
 *
 * @name HttpProvider
 *
 * @description The HTTP Provider allows sending requests using HTTP to a HTTP RPC server TCP port. It does not support subscriptions so you won't be able to listen to events such as new blocks or balance changes. It is usually preferrable using the [[WsProvider]].
 *
 * @example
 * <BR>
 *
 * ```javascript
 * import Api from '@polkadot/api/promise';
 * import HttpProvider from '@polkadot/rpc-provider/http';
 *
 * const provider = new HttpProvider('http://127.0.0.1:9933');
 * const api = new Api(provider);
 * ```
 *
 * @see [[WsProvider]]
 */
class HttpProvider {
    /**
     * @param {string} endpoint The endpoint url starting with http://
     */
    constructor(endpoint = defaults_1.default.HTTP_URL) {
        util_1.assert(/^(https|http):\/\//.test(endpoint), `Endpoint should start with 'http://', received '${endpoint}'`);
        this.coder = new coder_1.default();
        this.endpoint = endpoint;
    }
    /**
     * @summary `true` when this provider supports subscriptions
     */
    get hasSubscriptions() {
        return false;
    }
    /**
     * @description Returns a clone of the object
     */
    clone() {
        throw new Error('Unimplemented');
    }
    /**
     * @description Manually disconnect from the connection
     */
    disconnect() {
        // noop
    }
    /**
     * @summary Whether the node is connected or not.
     * @return {boolean} true if connected
     */
    isConnected() {
        return true;
    }
    /**
     * @summary Events are not supported with the HttpProvider, see [[WsProvider]].
     * @description HTTP Provider does not have 'on' emitters. WebSockets should be used instead.
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    on(type, sub) {
        l.error('HTTP Provider does not have \'on\' emitters, use WebSockets instead');
        return () => {
            // noop
        };
    }
    /**
     * @summary Send HTTP POST Request with Body to configured HTTP Endpoint.
     */
    send(method, params) {
        return __awaiter(this, void 0, void 0, function* () {
            const body = this.coder.encodeJson(method, params);
            const response = yield fetch(this.endpoint, {
                body,
                headers: {
                    Accept: 'application/json',
                    'Content-Length': `${body.length}`,
                    'Content-Type': 'application/json'
                },
                method: 'POST'
            });
            util_1.assert(response.ok, `[${response.status}]: ${response.statusText}`);
            const result = yield response.json();
            return this.coder.decodeResponse(result);
        });
    }
    /**
     * @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/require-await
    subscribe(types, method, params, cb) {
        return __awaiter(this, void 0, void 0, function* () {
            l.error(ERROR_SUBSCRIBE);
            throw new Error(ERROR_SUBSCRIBE);
        });
    }
    /**
     * @summary Subscriptions are not supported with the HttpProvider, see [[WsProvider]].
     */
    // eslint-disable-next-line @typescript-eslint/no-unused-vars,@typescript-eslint/require-await
    unsubscribe(type, method, id) {
        return __awaiter(this, void 0, void 0, function* () {
            l.error(ERROR_SUBSCRIBE);
            throw new Error(ERROR_SUBSCRIBE);
        });
    }
}
exports.default = HttpProvider;
