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());
    });
};
import { ApduResponse } from '@iotize/tap/client/api';
import { NumberConverter, TapClient } from '@iotize/tap/client/impl';
import { Subject } from 'rxjs';
import { debug } from '../logger';
import { ServiceCallRunner } from './service-call-runner';
import { ServiceContainer } from './service-container';
import { NFC_PAIRING_COMMAND } from './tap-config';
import { TapError } from './tap-errors';
const TAG = 'Device';
/**
 *
 */
export class Tap {
    constructor(client) {
        this._events = new Subject();
        this._client = client;
        this._lwm2m = new ServiceCallRunner(this.client);
        this.service = new ServiceContainer(this._lwm2m);
        // 'service', (context) => new ServiceContainer(context.tap.lwm2m)
        // this._scramInterceptor = new ScramInterceptor(
        //     this._services.scram,
        //     this.apiConfig
        // );
        // this._client.addInterceptor(this._scramInterceptor);
        // this._initCache();
        // this._converterProvider = new ConverterProvider(PathToTypeMap, DefaultConverterMap);
    }
    get events() {
        return this._events.asObservable();
    }
    get client() {
        return this._client;
    }
    get lwm2m() {
        return this._lwm2m;
    }
    set client(client) {
        this._client = client;
        this._lwm2m.client = client;
        // this._services.client = client;
    }
    notifyEvent(event) {
        this._events.next(event);
    }
    static create() {
        return new Tap(TapClient.create());
    }
    static fromProtocol(protocol) {
        const client = TapClient.create();
        client.addComProtocol(protocol);
        return new Tap(client);
    }
    get protocol() {
        return this.client.getCurrentProtocol();
    }
    /**
     * Connect with the given communication protocol
     * TODO what if there is already a connected communication protocol
     * @param protocol
     */
    connect(protocol) {
        debug(TAG, 'connecting...');
        // this._clearCache();
        if (protocol) {
            this.client.addComProtocol(protocol, 'default');
        }
        return this._client.connect().toPromise();
    }
    /**
     * Disconnect device
     */
    disconnect() {
        debug(TAG, 'disconnecting...');
        // if (options.clearCache) {
        //     this.clearCache();
        // }
        // if (options.clearSession) {
        //     this.clearSession();
        // }
        return this._client.disconnect().toPromise();
    }
    isConnected() {
        if (!this._client) {
            return false;
        }
        return this._client.isConnected();
    }
    /**
     * Configure current tap instance thanks to a TapConfigurator
     * @param configurator
     */
    configure(configurator) {
        return configurator.configure(this).toPromise();
    }
    /**
     *
     * @param protocol
     */
    useComProtocol(protocol) {
        this.client.useComProtocol(protocol);
        return this;
    }
    /**
     * Send an NFC pairing request
     */
    nfcPairing() {
        return __awaiter(this, void 0, void 0, function* () {
            const comProtocol = yield this.client.getCurrentProtocol();
            const response = yield comProtocol.send(NFC_PAIRING_COMMAND).toPromise();
            if (response.length !== 2) {
                throw TapError.nfcPairingError(`Tap responded with a frame size of ${response.length} byte(s) but expecting 2 bytes.`);
            }
            const statusCode = NumberConverter.uint16().decode(response);
            if (statusCode !== ApduResponse.Status.OK) {
                throw TapError.nfcPairingError(`Tap responded with an invalid APDU response status 0x${statusCode.toString(16)}.`);
            }
            return response;
        });
    }
}
Tap.TAG = 'Tap';
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGFwLmpzIiwic291cmNlUm9vdCI6Im5nOi8vQGlvdGl6ZS90YXAvIiwic291cmNlcyI6WyJsaWIvdGFwLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7OztBQUFBLE9BQU8sRUFBRSxZQUFZLEVBQXNCLE1BQU0sd0JBQXdCLENBQUM7QUFDMUUsT0FBTyxFQUFFLGVBQWUsRUFBRSxTQUFTLEVBQUUsTUFBTSx5QkFBeUIsQ0FBQztBQUVyRSxPQUFPLEVBQWMsT0FBTyxFQUFFLE1BQU0sTUFBTSxDQUFDO0FBRTNDLE9BQU8sRUFBRSxLQUFLLEVBQUUsTUFBTSxXQUFXLENBQUM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