let libFS = require("fs");

fcf.module({
  name: "fcfManagement:templates/pages/translations/files-tab.receive.js",
  dependencies: [],
  module: function(){
    var self = this;

    fcf.addException("FCF_MANAGER_FAILD_CREATE_TRANSLATE_FILE", "Сouldn't create translation file");

    return {
      receive: function(a_fields, a_files){
        let filesInfo  = [];
        fcf.each(a_fields.files, (a_key, a_fileInfo)=>{
          filesInfo.push({
            path:     a_fileInfo.path,
            language: a_fileInfo.language,
            enable:   a_fileInfo.enable,
            editable: a_fileInfo.editable,
            system:   a_fileInfo.system
          });
        })

        return fcf.actions()
        .each(a_fields.newFiles, (a_filePath, a_value, a_res, a_act) => {
          let file = a_fields.files[fcf.find(a_fields.files, (k, v)=>{ return v.path == a_filePath})];
          if (!file){
            a_act.complete();
            return;
          }
          libFS.writeFile(
            fcf.getPath(file.path),
            JSON.stringify({language: file.language, translations: {}}, false, 2), 
            "utf8",
            (a_error)=>{
              if (a_error){
                a_act.error(new fcf.Exception("FCF_MANAGER_FAILD_CREATE_TRANSLATE_FILE"));
                return;
              }
              a_act.complete();
            }
          );
        })
        .each(a_fields.appendFiles, (a_filePath, a_index, a_res, a_act) => {
          libFS.copyFile(
            a_files[a_index].path, 
            fcf.getPath(a_filePath), 
            (a_error) => {
              if (a_error) {
                a_act.error(a_error);
                return;
              }
              a_act.complete();
            }
          );
        })
        .each(a_fields.deleteFiles, (a_filePath, a_value, a_res, a_act) => {
          libFS.unlink(
            fcf.getPath(a_filePath), 
            (a_error) => {
              if (a_error) {
                a_act.error(a_error);
                return;
              }
              a_act.complete();
            }
          );
        })
        .then(()=>{
          return fcf.setSystemVariable("fcf:languageFiles", filesInfo)
          .then((a_res)=>{
            return fcf.application.getEventChannel().send("translations")
            .then(()=>{
              return a_res;
            })
          })
        })
      }
    }
  }
});
