"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VoiceImpl = void 0;
/**
 * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
 * http://github.com/fonoster/fonoster
 *
 * This file is part of Fonoster
 *
 * Licensed under the MIT License (the "License");
 * you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    https://opensource.org/licenses/MIT
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const common_1 = require("@fonoster/common");
const uuid_1 = require("uuid");
class VoiceImpl {
    constructor(sessionRef, voice) {
        this.voice = voice;
        this.sessionRef = sessionRef;
        this.playbackRef = (0, uuid_1.v4)();
    }
    async answer() {
        await this.voice.answer();
    }
    async hangup() {
        await this.voice.hangup();
    }
    async say(text) {
        await this.voice.say(text, { playbackRef: this.playbackRef });
    }
    async sgather() {
        const stream = await this.voice.sgather({
            source: common_1.StreamGatherSource.SPEECH
        });
        this.sgatherStream = {
            stop: async () => {
                stream.close();
                stream.cleanup(() => { });
            },
            onData: (cb) => {
                stream.onPayload((payload) => {
                    cb({
                        speech: payload.speech,
                        responseTime: payload.responseTime
                    });
                });
            }
        };
        return this.sgatherStream;
    }
    async stream() {
        const stream = await this.voice.stream();
        this.vadStream = {
            stop: async () => {
                stream.close();
                stream.cleanup(() => { });
            },
            onData: (cb) => {
                stream.onPayload((payload) => {
                    cb(payload.data);
                });
            }
        };
        return this.vadStream;
    }
    async transfer(to, options) {
        const { record, timeout } = options;
        const effectiveOptions = {
            recordDirection: record ? common_1.DialRecordDirection.BOTH : undefined,
            timeout
        };
        await this.voice.dial(to, effectiveOptions);
    }
    async stopSpeech() {
        await this.voice.playbackControl(this.playbackRef, common_1.PlaybackControlAction.STOP);
    }
    async stopStreams() {
        await this.vadStream.stop();
        await this.sgatherStream.stop();
    }
}
exports.VoiceImpl = VoiceImpl;
