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 || response.length !== 2) {
                throw TapError.nfcPairingError(`Tap responded with a frame size of ${(response === null || response === void 0 ? void 0 : response.length) || 0} 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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGFwLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2xpYi90YXAudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7O0FBQUEsT0FBTyxFQUFFLFlBQVksRUFBc0IsTUFBTSx3QkFBd0IsQ0FBQztBQUMxRSxPQUFPLEVBQUUsZUFBZSxFQUFFLFNBQVMsRUFBRSxNQUFNLHlCQUF5QixDQUFDO0FBRXJFLE9BQU8sRUFBYyxPQUFPLEVBQUUsTUFBTSxNQUFNLENBQUM7QUFFM0MsT0FBTyxFQUFFLEtBQU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