let libFS = require("fs");

fcf.module({
  name: "fcfManagement:templates/pages/translations/files-tab.receive.js",
  dependencies: ["fcf:NSystem/fs.js"],
  module: function(fs){
    fcf.addException("FCF_MANAGER_FAILD_CREATE_TRANSLATE_FILE", "Сouldn't create translation file");

    return class Handler {
      receive(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;
          }
          fs.writeFile(
            file.path,
            JSON.stringify({language: file.language, translations: {}}, false, 2),
            undefined,
            (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) => {
          fs.copyFile(
            a_files[a_index].path,
            a_filePath,
            undefined,
            (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) => {
          fs.deleteFile(
            fcf.getPath(a_filePath),
            undefined,
            (a_error) => {
              if (a_error) {
                a_act.error(a_error);
                return;
              }
              a_act.complete();
            }
          );
        })
        .then(()=>{
          return fcf.application.setSystemVariable("fcf:languageFiles", filesInfo)
          .then((a_res)=>{
            return fcf.application.getEventChannel().send("fcfManagement_translations")
            .then(()=>{
              return a_res;
            })
          })
        })
      }
    }
  }
});
