import config from "./config";
import TTSFactory from "./TTSFactory";
const fs = require("fs");
const baseConfig = require(`../../../config/config.default.js`);


export class TTS{
    constructor(params) {
        this.params = params;
        this.sp = params.config.endpoint.sp||"tencent";
      }
    async textToVoice(data){
        this.TTSObject = TTSFactory.getInstance(
            this.sp,
            Object.assign({}, config[this.sp], this.params)
        );
        var result = await this.TTSObject.textToVoice(data);
        return result;
    }
}

export class TaskTTS{
    constructor(params) {
        this.params = params;
        this.sp = params.config.endpoint.sp||"tencent";
      }
    async createTtsTask(text){
        this.TTSObject = TTSFactory.getInstance(
            this.sp,
            Object.assign({}, config[this.sp], this.params)
        );
        var result = await this.TTSObject.createTtsTask(text);
        return result;
    }
    async describeTtsTaskStatus(taskId){
        var result = await this.TTSObject.describeTtsTaskStatus(taskId);
        return result;
    }
}

export async function adapterTTS(data,oSink,oSource){
    if (oSink.config.endpoint.sp == "tencent") {
        if(oSource.config.mediaType=="file"){
            data.result=await transferFile(data.Audio,oSink.config.params.Codec||"wav");
        }else if(oSource.config.mediaType=="base64"){
            data.result={base64:data.Audio};
            delete data.Audio;
        }
    }

    return data;
}

async function transferFile(base64, decode) {
    var result={}
    var fileName = "TTSResult" + new Date().getTime() + '.' + decode;
    var filePath = "./public/audio/" + fileName;
    fs.writeFileSync(filePath, base64, { encoding: 'base64' });
    result.url = baseConfig.config.url + "/audio/" + fileName;
    return result;
}
