function translation=trans(varargin)
% TRANSLATE —— UESTC 2020.12.30 
% 使用百度翻译API完成翻译,需要提供百度开发者ID与密钥用于调用通用翻译API,并且需要开通通用翻译服务;
% 该函数可输入0至3个参数,可以输入字符向量或字符串标量,翻译返回结果将复制到剪切板;
% trans     ———从剪切板读取原文数据,默认中英互译,其余外文一律翻译为中文;
% trans('help')     ———函数保留字,用于查询支持翻译的语种的列表;
% trans('Language') ———仅输入可识别的语种缩写,从剪切板复制原文,并翻译到输入语种;
% trans('Text')     ———将Text作为原文,默认中英互译,其余外文一律翻译为中文;
% trans('Language1','Language2') ———输入2种可识别语种,从剪切板复制原文,从语种1翻译到语种2,若语种1与原文语种不匹配,将输出原文;
% trans('Language','Text') ———输入可识别语种和原文,将原文翻译到该语种,语种和翻译原文输入次序可调换;
% trans('Text1','Text2') ———输入为两段原文时,仅翻译第一个输入并给出警告,默认中英互译,其余外文一律翻译为中文;
% trans('Language1','Language2','Text')
%     ———可调换输入参数位置,将Text原文由语种1翻译至语种2,但两种语种取前一个作为原文语,后一种作为译文语种;
%        三输入参数其他情况:
%        输入3语种: 仅取前两者作为原文与译文语种,复制剪切板内容作为原文;
%        输入3原文: 仅翻译第一段原文,默认中英互译,其余外文一律翻译为中文;
%        输入1语种和2原文: 仅翻译第一段原文至指定语种;
%        
% 通用翻译API接口：
% 每月前200万字符免费;
% 超出后仅收取超出部分费用,49元/百万字符;
% QPS(最大并发量)：10
% 为保证翻译质量,请将单次请求长度控制在6000bytes以内(汉字约为2000个);
% 字数统计与Microsoft Word软件-字数统计-字符数(计空格)保持一致;
%
% 常见语种列表：
%     中文  zh
%     英语  en
%     日语  jp
%     德语  de
%     俄语  ru
%     法语  fra
%     韩语  kor
%   文言文  wyw
% 繁体中文  cht
% ...
%


%请输入个人开发者ID与密钥,切勿公开！
appid = '';
secretKey = '';

if isempty(appid) || isempty(secretKey)
    error('请先在函数脚本中给出个人开发者ID及密钥！')
end

Lang =["zh","en","jp","de","fra","kor","yue","cht","wyw",...
       "ru","th","pt","el","it","bul","fin","slo","ara",...
       "nl","est","cs","swe","vie","spa","rom","pl","dan","hu"]; %支持的所有语种

if nargin == 0
    %无输入，默认从剪切板导入原文，默认为中英互译
    q = clipboard("paste");
    fromLang = 'auto';    %原文语种
    toLang   = ZhOrEn(q); %译文语种,智能识别语种,中英互译！
elseif nargin == 1
   if string(varargin) == "help"
      %输入help时，显示全部支持的语种
      LangZH = ["中文","英语","日语","德语","法语","韩语","粤语","繁体中文",...
          "文言文","俄语","泰语","葡萄牙语","希腊语","意大利语","保加利亚语",...
          "芬兰语","斯洛文尼亚语","阿拉伯语","荷兰语","爱沙尼亚语","捷克语",...
          "瑞典语","越南语","西班牙语","罗马尼亚语","波兰语","丹麦语","匈牙利语"]; %语种中文名
      translation = table([Lang(1:14)',LangZH(1:14)',Lang(15:28)',LangZH(15:28)'],...
                    'VariableNames',{'Language comparison table'});
      return
   elseif ismember(lower(varargin{1}),Lang)  %输入译文语种
      q = clipboard("paste");
      if isempty(q)    %剪切板为空，返回错误信息！
          error('Clipboard data is empty or non character data!')
      else
          fromLang = 'auto';  %原文语种
          toLang = varargin{1};
      end
   else
      %输入待翻译原文,默认为中英互译
      q = varargin{1};
      fromLang = 'auto';
      toLang = ZhOrEn(q);
   end
elseif nargin == 2 
    qi=cellfun(@(x)ismember(lower(x),Lang),varargin);
    if sum(qi) == 2 
        %输入原文与译文语种,原文由剪切板导入！
        q = clipboard("paste");
        fromLang = varargin{1};
        toLang = varargin{2};
    elseif sum(qi) == 1
        %输入翻译原文和译文语种！
        textID = (qi == 0);
        q = varargin{textID};
        fromLang = 'auto';
        toLang = varargin{~textID};
    else
        %无有效译文语种！默认第一输入为原文！
        warning('No translation language input, translate the first paragraph only!')
        q = varargin{1};
        fromLang = 'auto';
        toLang = ZhOrEn(q);
    end  
elseif nargin == 3
    qi=cellfun(@(x)ismember(lower(x),Lang),varargin);
    if sum(qi) == 3
        %输入3种语种
        warning(['Input too many languages, only input the first two as parameters!'...
                    ' The original texts were imported by the clipboard!'])
        q = clipboard("paste"); %TODO 识别语种
        fromLang = varargin{1};
        toLang = varargin{2};
    elseif sum(qi) == 2
        %输入2种语种
        textID = (qi == 0);
        LangID =find(qi == 1);
        q = varargin{textID};
        fromLang = varargin{LangID(1)};
        toLang = varargin{LangID(2)};
    elseif sum(qi) == 1
        %输入1种语种,仅翻译第一段原文
        warning('Maybe two original paragraphs, only translate the first paragraph!')
        TextID =find(qi == 0);
        q = varargin{TextID(1)};
        fromLang = 'auto';
        toLang = varargin{qi};
    else
        %输入0种语种，仅翻译第一段，默认中英互译，否则一律翻译为中文
        warning('Maybe three original paragraphs, only translate the first paragraph!')
        TextID =find(qi == 0);
        q = varargin{TextID(1)};
        fromLang = 'auto';
        toLang = ZhOrEn(q);
    end
else
    %超过4个输入！
    error('Too much input!')
end
myurl = 'https://fanyi-api.baidu.com/api/trans/vip/translate';
salt = randi([32768, 65536]);
sign = [appid, char(q), num2str(salt), secretKey];
sign = lower(mlreportgen.utils.hash(sign)); %计算MD5值
myurl = [myurl ,...
    '?appid=' ,appid ,...
    '&q=' ,urlencode(q) ,...
    '&from=',char(fromLang),...
    '&to=' ,char(toLang) ,...
    '&salt=' ,num2str(salt),...
    '&sign=' ,char(sign)]; %合并网址
data = webread(myurl); %请求参数并输出
translation = data.trans_result;
clipboard("copy",translation.dst) %将翻译内容复制到剪切板
end

%

function toLang=ZhOrEn(q)
%判别输入字符串是含中文还是全部是外文
    Lang=cellfun(@(x)contains(string(x),...
        string(char((hex2dec('4e00'):hex2dec('9fa5'))'))),...
        cellstr(string(q)));
    if Lang == 1
        toLang='en';
    else
        toLang='zh';
    end
end