import { MD5 } from "./md5";

const { TranslateFactory } = require("./TranslateFactory");


export class Translate {
    constructor(params) {
        this.params = params;
        this.sp = params.config.endpoint.sp || "baidu";
    }
    async query() {
        this.translate = TranslateFactory.getInstance(this.sp, this.params);
        return await this.translate.query();
    }
}

export async function getTranslateOptions(data, oSink) {
    if (oSink.config.endpoint.sp == "baidu") {
        var appid = oSink.token.appId;
        var key = oSink.token.secretKey;
        var salt = (new Date).getTime().toString();
        var query = data.query;
        // 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
        var from = data.from || oSink.config.params.from || 'auto';
        var to = data.to || oSink.config.params.to || 'en';
        var str1 = appid + query + salt + key;
        var sign = MD5(str1);
        var options = {
            url: oSink.config.endpoint.url,
            method: 'GET',
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
              },
            params: {
                q: query,
                appid: appid,
                salt: salt,
                from: from,
                to: to,
                sign: sign
            }
        }

        return options;

    }
}

export async function adapterTranslate(data, oSink) {
    if (oSink.config.endpoint.sp == "baidu") {
        data.result={text:data.trans_result[0].dst};
    }

    return data;
}

