<!--
 Program: TransPopup.vue
 Author: SDL
 Description: translation screen(by U Trans)
-->
<template>
<div class="modal" tabindex="-1">
<div class="modal-dialog modal-xl">
  <div class="modal-content">
    <!-- contents -->
    <div class="modal-header">
      <h5 class="modal-title">{{ $t('sdl.translation.translation') }}</h5>
      <button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" @click="close"></button>
    </div>
    <div class="modal-body">
      <div class="row mb-2">
        <div class="col-5">
          <div class="input-group">
            <select
              class="form-select"
              style="width:150px"
              v-model="transParam.source.language"
              @change="changeSourceLang"
            >
              <option
                :value="sourceCode.code"
                v-for="sourceCode in transParam.source.langList"
                :key="sourceCode.codeId"
                >{{ getLabel(sourceCode) }}</option
              >
            </select>
            <button
              class="btn btn-outline-secondary"
              type="button"
              data-toggle="tooltip"
              data-placement="bottom"
              :title="[$t('sdl.translation.langConversion')]"
              @click="setLanguageChange"
            >
              <i class="bi bi-arrow-left-right"></i>
            </button>
            <select class="form-select" style="width:150px" v-model="transParam.target.language">
              <option
                :value="targetCode.code"
                v-for="targetCode in transParam.target.langList"
                :key="targetCode.codeId"
                >{{ getLabel(targetCode) }}</option
              >
            </select>
          </div>
        </div>
        <div class="col-5">
          <button class="btn btn-primary ms-1" type="submit" @click="getTranslation">
          {{ $t('sdl.translation.translate') }}</button>
        </div>
        <div class="col-2 text-end">
          <button class="btn btn-outline-secondary" type="submit" @click.stop.prevent="copyText">
            {{ $t('sdl.translation.copy') }}
          </button>
        </div>
      </div>
      <div class="row">
        <div class="col-6">
          <div class="ui--translate-target">
            <textarea class="form-control" rows="15" placeholder="" v-model="transParam.source.text"></textarea>
            <button class="btn ui--btn-icon-lg position-absolute top-0 end-0" :title="[$t('sdl.translation.clearText')]" @click="textClear">
              <i class="bi bi-x"></i>
            </button>
          </div>
        </div>
        <div class="col-6">
          <div class="ui--translate-result">
            <textarea
              id="targetText"
              class="form-control"
              rows="15"
              :placeholder="[$t('sdl.translation.contentDisplayed')]"
              v-model="transParam.target.text"
            ></textarea>
          </div>
        </div>
      </div>
      <div class="row mt-2">
        <div class="col-12">
          <small class="text-muted">Powered by UTrans (utrans@samsung.com) </small>
        </div>
      </div>
    </div>
  </div>
</div>
</div>
</template>
<script>
import axios from 'axios';
import _ from 'lodash';
import SDLUtil from '@/utils/SDLUtil';
import SDLLocale from '@/mixin/SDLLocale';

export default {
  data() {
    return {
      transParam: {
        source: {
          language: '',
          text: '',
          langList: [],
        },
        target: {
          language: '',
          text: '',
          langList: [],
        },
      },
      baseLangList: [],
      translateText: '',
      completeTrans: false,
    };
  },
  mixins: [SDLLocale],
  methods: {
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Set the target language combo when the source language combo changes
     */
    changeSourceLang() {
      const sourceLang = this.transParam.source.language === '' ? 'ko' : this.transParam.source.language;
      const targetLang = this.transParam.target.language === '' ? 'en' : this.transParam.target.language;

      let exclusionLang = [];

      /**
       * Branch to match supported translation directions
       */
      if (sourceLang !== 'ko') {
        if (sourceLang === 'vi' || sourceLang === 'ja') {
          exclusionLang = this.baseLangList.filter(codeObj => codeObj.code !== 'ko').map(code => code.code);
        } else {
          exclusionLang.push('ja');
          exclusionLang.push('vi');
        }
      }

      // Exclude settings if the source select box value is specified in the exclusion array
      if (!_.includes(exclusionLang, sourceLang)) {
        exclusionLang.push(sourceLang);
      }

      const tempCodeList = this.baseLangList.slice();

      /**
       * Exclude excluded language codes from the default language code
       */
      exclusionLang.forEach(lang => {
        tempCodeList.splice(_.findIndex(tempCodeList, codeObj => codeObj.code === lang), 1);
      });

      // Set target select box
      this.transParam.target.langList = tempCodeList;

      // Specify the default selection value
      if (targetLang && this.transParam.target.langList.findIndex(codeObj => codeObj.code === targetLang) > -1) {
        this.transParam.target.language = targetLang;
      } else {
        this.transParam.target.language = this.transParam.target.langList[0].code;
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: language conversion(source <-> target)
     */
    setLanguageChange() {
      const sourceLang = this.transParam.source.language;
      const sourceText = this.transParam.source.text;

      // language(source <-> target)
      this.transParam.source.language = this.transParam.target.language;
      this.transParam.target.language = sourceLang;

      // target selectbox setting
      this.changeSourceLang();

      // textarea(source <-> target)
      this.transParam.source.text = this.transParam.target.text;
      this.transParam.target.text = sourceText;
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: textarea initialization
     */
    textClear() {
      this.transParam.source.text = '';
      this.transParam.target.text = '';
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Execute the translation api execution function
     */
    getTranslation() {
      const inputText = this.transParam.source.text;

      // If there is no translation character, initialize API call X and translation result value
      if (inputText.length === 0) {
        this.transParam.target.text = inputText;
        return;
      }

      const inputTextArray = inputText.split('\n');

      if (inputTextArray.length > 0) {
        // Launch Loading bar
        SDLUtil.showLoadingBar(true);

        Promise.all(inputTextArray.map(this.callTranslateApi))
          .then(data => {
            // init target textarea
            this.transParam.target.text = '';

            data.some(result => {
              if (_.isEmpty(result.errorCode) || result.errorCode === '' || result.errorCode === '1111') {
                this.transParam.target.text = `${this.transParam.target.text}${result.result}\n`;
                return true;
              }
              if (result.errorCode === '2001') {
                this.transParam.target.text = `${this.transParam.target.text}\n`;
                return true;
              }
              if (result.errorCode === '2002') {
                SDLUtil.alert('sdl.translation.inputByteExceeded');
                return true;
              }
              return false;
            });

            // Remove Loading bar
            SDLUtil.showLoadingBar(false);
          })
          .catch(err => {
            // Remove Loading bar
            SDLUtil.showLoadingBar(false);
            // Call error alert
            SDLUtil.errorAlert(err);
          });
      }
    },
    /**
     * param: nothing
     * return: nothing
     * exception: nothing
     * description: Close
     */
    close() {
      window.close();
    },
    /**
     * param: string
     * return: nothing
     * exception: Call error alert
     * description: Calling the Translation API
     */
    callTranslateApi(query) {
      return new Promise((resolve, reject) => {
        /**
         * Calling the Translation API
         */
        axios({
          method: 'POST',
          url: `${SDLUtil.API_URL}/translate`,
          headers: { 'Content-Type': 'application/json' },
          data: JSON.stringify({
            source: this.transParam.source.language,
            target: this.transParam.target.language,
            query,
          }),
        })
          .then(({ data }) => {
            resolve(data);
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    /**
     * param: nothing
     * return: nothing
     * exception: Call error alert
     * description: Copy translated sentences to the clipboard
     */
    copyText() {
      const targetText = document.querySelector('#targetText');
      targetText.setAttribute('type', 'text');
      targetText.select();

      try {
        const successful = document.execCommand('copy');
        const msg = successful ? 'successful' : 'unsuccessful';
        SDLUtil.alert('sdl.translation.copyMessage');
        console.log(msg);
      } catch (err) {
        SDLUtil.errorAlert(err);
        console.log('copy error');
      }

      /* unselect the range */
      targetText.setAttribute('type', 'hidden');
      window.getSelection().removeAllRanges();
    },
  },
  created() {
    // common code
    axios.get(`${SDLUtil.API_URL}/commcode/groupcodes/TRANS_LANG/commcodes`).then(({ data }) => {
      /**
       * Exclude language detection
       */
      this.baseLangList = data.filter(code => code.code !== 'zz');
      this.transParam.source.langList = this.baseLangList.slice();
      this.transParam.target.langList = this.baseLangList.slice();

      this.transParam.source.language = 'ko';
      this.transParam.target.language = 'en';

      this.changeSourceLang();
    });
  },
};
</script>
<style>
.modal {
  display: block;
}
</style>
