// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
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 { MessageType } from "../common/Exports";
import { CancellationErrorCode, ConversationTranscriptionCanceledEventArgs, PropertyCollection, PropertyId, ResultReason, SpeechRecognitionEventArgs, SpeechRecognitionResult, } from "../sdk/Exports";
import { CancellationErrorCodePropertyName, ConversationServiceRecognizer } from "./Exports";
import { SpeechConnectionMessage } from "./SpeechConnectionMessage.Internal";
// eslint-disable-next-line max-classes-per-file
export class TranscriptionServiceRecognizer extends ConversationServiceRecognizer {
    constructor(authentication, connectionFactory, audioSource, recognizerConfig, transcriber) {
        super(authentication, connectionFactory, audioSource, recognizerConfig, transcriber);
        this.privTranscriberRecognizer = transcriber;
        this.sendPrePayloadJSONOverride = (connection) => this.sendTranscriptionStartJSON(connection);
        if (this.privRecognizerConfig.parameters.getProperty(PropertyId.SpeechServiceResponse_RequestWordLevelTimestamps) === "true") {
            this.privSpeechContext.setWordLevelTimings();
        }
    }
    sendSpeechEventAsync(info, command) {
        return __awaiter(this, void 0, void 0, function* () {
            if (!!this.privRequestSession.isRecognizing) {
                const connection = yield this.fetchConnection();
                yield this.sendSpeechEvent(connection, this.createSpeechEventPayload(info, command));
            }
        });
    }
    processTypeSpecificMessages(connectionMessage) {
        return this.processSpeechMessages(connectionMessage);
    }
    handleRecognizedCallback(result, offset, sessionId) {
        try {
            const event = new SpeechRecognitionEventArgs(result, offset, sessionId);
            this.privTranscriberRecognizer.recognized(this.privTranscriberRecognizer, event);
            if (!!this.privSuccessCallback) {
                try {
                    this.privSuccessCallback(result);
                }
                catch (e) {
                    if (!!this.privErrorCallback) {
                        this.privErrorCallback(e);
                    }
                }
                // Only invoke the call back once.
                // and if it's successful don't invoke the
                // error after that.
                this.privSuccessCallback = undefined;
                this.privErrorCallback = undefined;
            }
            /* eslint-disable no-empty */
        }
        catch (error) {
            // Not going to let errors in the event handler
            // trip things up.
        }
    }
    handleRecognizingCallback(result, duration, sessionId) {
        try {
            const ev = new SpeechRecognitionEventArgs(result, duration, sessionId);
            this.privTranscriberRecognizer.recognizing(this.privTranscriberRecognizer, ev);
            /* eslint-disable no-empty */
        }
        catch (error) {
            // Not going to let errors in the event handler
            // trip things up.
        }
    }
    // Cancels recognition.
    cancelRecognition(sessionId, requestId, cancellationReason, errorCode, error) {
        const properties = new PropertyCollection();
        properties.setProperty(CancellationErrorCodePropertyName, CancellationErrorCode[errorCode]);
        if (!!this.privTranscriberRecognizer.canceled) {
            const cancelEvent = new ConversationTranscriptionCanceledEventArgs(cancellationReason, error, errorCode, undefined, sessionId);
            try {
                this.privTranscriberRecognizer.canceled(this.privTranscriberRecognizer, cancelEvent);
                /* eslint-disable no-empty */
            }
            catch (_a) { }
        }
        if (!!this.privSuccessCallback) {
            const result = new SpeechRecognitionResult(requestId, ResultReason.Canceled, undefined, // Text
            undefined, // Duration
            undefined, // Offset
            undefined, // Language
            undefined, // Language Detection Confidence
            undefined, // Speaker Id
            error, undefined, // Json
            properties);
            try {
                this.privSuccessCallback(result);
                this.privSuccessCallback = undefined;
                /* eslint-disable no-empty */
            }
            catch (_b) { }
        }
    }
    // Encapsulated for derived service recognizers that need to send additional JSON
    sendTranscriptionStartJSON(connection) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.sendSpeechContext(connection, true);
            const info = this.privTranscriberRecognizer.getConversationInfo();
            const payload = this.createSpeechEventPayload(info, "start");
            yield this.sendSpeechEvent(connection, payload);
            yield this.sendWaveHeader(connection);
            return;
        });
    }
    sendSpeechEvent(connection, payload) {
        const speechEventJson = JSON.stringify(payload);
        if (speechEventJson) {
            return connection.send(new SpeechConnectionMessage(MessageType.Text, "speech.event", this.privRequestSession.requestId, "application/json", speechEventJson));
        }
        return;
    }
    createSpeechEventPayload(info, command) {
        const eventDict = { id: "meeting", name: command, meeting: info.conversationProperties };
        eventDict.meeting.id = info.id;
        eventDict.meeting.attendees = info.participants;
        eventDict.meeting.record = info.conversationProperties.audiorecording === "on" ? "true" : "false";
        return eventDict;
    }
}

//# sourceMappingURL=TranscriptionServiceRecognizer.js.map
