<commit_before><link rel="import" href="../../../../app-elements/static-common-data/redux-behaviors/common-static-data-redux-behavior.html">
<link rel="import" href="../../../../../bower_components/etools-behaviors/etools-logs-behavior.html">
<script>
  /**
   * Behavior used to add/edit expected results (result_links).
   *  - create cp output and ram indicators dialog
   *  - save new result or edit one by selecting a cp output and a available ram indicators
   */
  window.EtoolsPmpApp = window.EtoolsPmpApp || {};
  window.EtoolsPmpApp.Behaviors = window.EtoolsPmpApp.Behaviors || {};
  /** @polymerBehavior EtoolsPmpApp.Behaviors.ExpectedResultsImpl */
  EtoolsPmpApp.Behaviors.ExpectedResultsImpl = {
    properties: {
      interventionId: {
        type: Number
      },
      cpOutputRamIndicatorsEditElem: Object,
      selectedCpStructure: {
        type: String
      },
      cpOutputs: {
        type: Array,
        statePath: 'cpOutputs'
      },
      availableCpOutputs: {
        type: Array,
        computed: '_computeAvailableCpOutputs(cpOutputs, alreadySelectedCpOutputs, selectedCpStructure)'
      },
      alreadySelectedCpOutputs: {
        type: Array,
        value: []
      },
      mainDataPath: String
    },

    _computeAvailableCpOutputs: function(cpOutputs, alreadySelectedCpOutputs, selectedCpStructure) {
      let selectedCpStructureId = parseInt(selectedCpStructure, 10);
      return cpOutputs.filter(function(cp) {
        let notSelected = alreadySelectedCpOutputs.indexOf(cp.id) === -1;
        let belongsToCpStructure = true;
        if (selectedCpStructureId > 0 && selectedCpStructureId !== parseInt(cp.country_programme, 10)) {
          belongsToCpStructure = false;
        }
        return notSelected && belongsToCpStructure;
      });
    },

    setAlreadySelectedCpOutputs: function(resultsLength, results) {
      if (resultsLength > 0) {
        this.set('alreadySelectedCpOutputs', this._getSelectedCpOutputsIds(results || []));
      } else {
        this.set('alreadySelectedCpOutputs', []);
      }
    },

    // get selected cpoutputs ids
    _getSelectedCpOutputsIds: function(results) {
      let selectedCpOIds = [];
      if (results.length > 0) {
        results.forEach(function(result) {
          if (result.cp_output) {
            selectedCpOIds.push(result.cp_output);
          }
        });
      }
      return selectedCpOIds;
    },

    removeCpOutputRamIndicatorsDialog: function() {
      if (this.cpOutputRamIndicatorsEditElem) {
        Polymer.dom(document.querySelector('body')).removeChild(this.cpOutputRamIndicatorsEditElem);
      }
    },

    createAddEditCpOutputRamIndicatorsElement: function() {
      this.cpOutputRamIndicatorsEditElem = Polymer.dom(document.querySelector('body'))
          .querySelector('#cpOutputRamIndicatorsEditElem');
      if (!this.cpOutputRamIndicatorsEditElem) {
        this.cpOutputRamIndicatorsEditElem = document.createElement('result-cp-output-and-ram-indicators');
        this.cpOutputRamIndicatorsEditElem.setAttribute('id', 'cpOutputRamIndicatorsEditElem');

        this.cpOutputRamIndicatorsEditElem.set('toastEventSource', this);

        this.cpOutputRamIndicatorsEditElem.addEventListener('new-expected-result-added',
            this._handleNewResultAdded.bind(this));

        this.cpOutputRamIndicatorsEditElem.addEventListener('expected-result-updated',
            this._handleResultUpdated.bind(this));

        Polymer.dom(document.querySelector('body')).appendChild(this.cpOutputRamIndicatorsEditElem);
      }
    },

    openCpOutputAndRamIndicatorsDialog: function(expectedResultId, cpOutputId, ramIndicatorsIds, editIndex) {
      if (this.cpOutputRamIndicatorsEditElem) {
        this.cpOutputRamIndicatorsEditElem.resetData();

        this.cpOutputRamIndicatorsEditElem.set('interventionId', this.interventionId);
        this.cpOutputRamIndicatorsEditElem.set('expectedResultId', expectedResultId);
        this.cpOutputRamIndicatorsEditElem.set('selectedRamIndicatorsIds', ramIndicatorsIds);

        let availableCpOutputsOptions = this.availableCpOutputs.slice(0);
        if (cpOutputId) {
          /**
           * cpOutputId is valid => edit operation, include curent cpOutput in the availableCpOutputsOptions
           * as user might want to edit only the ram indicators
           */
          let currentCpOutputData = this.cpOutputs.find(function(cp) {
            return parseInt(cp.id, 10) === parseInt(cpOutputId, 10);
          });
          if (currentCpOutputData) {
            availableCpOutputsOptions.push(currentCpOutputData);
          } // else => old cp output, not found, it's data will be requested by the cp outputs dropdown

          // prevent ram indicators reset at first request, edit operation
          this.cpOutputRamIndicatorsEditElem.set('_preventRamIndicatorReset', true);
          this.cpOutputRamIndicatorsEditElem.set('editIndex', editIndex);
        }
        this.cpOutputRamIndicatorsEditElem.set('availableCpOutputs', availableCpOutputsOptions);
        this.cpOutputRamIndicatorsEditElem.set('selectedCpOutputId', cpOutputId);

        this.cpOutputRamIndicatorsEditElem.openDialog();
      }
    },

    _handleNewResultAdded: function(e) {
      e.stopImmediatePropagation();
      if (!this._canUpdateResult()) {
        return;
      }
      this.push('dataItems', e.detail.result);
    },

    _handleResultUpdated: function(e) {
      e.stopImmediatePropagation();
      if (!this._canUpdateResult()) {
        return;
      }
      this.set(['dataItems', e.detail.index, 'cp_output'], e.detail.result.cp_output);
      this.set(['dataItems', e.detail.index, 'ram_indicators'], e.detail.result.ram_indicators);
    },

    _canUpdateResult: function() {
      if (!this.get('dataItems')) {
        this.logError('dataItems is undefined or null. You must have dataItems(Array of result_links) defined ' +
            'to use this behavior.', 'results-behavior');
        return false;
      }
      return true;
    }

  };

  /** @polymerBehavior EtoolsPmpApp.Behaviors.ExpectedResults */
  EtoolsPmpApp.Behaviors.ExpectedResults = [
    EtoolsLogsBehavior,
    EtoolsPmpApp.Behaviors.EtoolsDataReduxStore,
    EtoolsPmpApp.Behaviors.ExpectedResultsImpl
  ]
</script>
<commit_msg>Fix error on adding the first Pd output or SSFA expected result<commit_after><link rel="import" href="../../../../app-elements/static-common-data/redux-behaviors/common-static-data-redux-behavior.html">
<link rel="import" href="../../../../../bower_components/etools-behaviors/etools-logs-behavior.html">
<script>
  /**
   * Behavior used to add/edit expected results (result_links).
   *  - create cp output and ram indicators dialog
   *  - save new result or edit one by selecting a cp output and a available ram indicators
   */
  window.EtoolsPmpApp = window.EtoolsPmpApp || {};
  window.EtoolsPmpApp.Behaviors = window.EtoolsPmpApp.Behaviors || {};
  /** @polymerBehavior EtoolsPmpApp.Behaviors.ExpectedResultsImpl */
  EtoolsPmpApp.Behaviors.ExpectedResultsImpl = {
    properties: {
      interventionId: {
        type: Number
      },
      cpOutputRamIndicatorsEditElem: Object,
      selectedCpStructure: {
        type: String
      },
      cpOutputs: {
        type: Array,
        statePath: 'cpOutputs'
      },
      availableCpOutputs: {
        type: Array,
        computed: '_computeAvailableCpOutputs(cpOutputs, alreadySelectedCpOutputs, selectedCpStructure)'
      },
      alreadySelectedCpOutputs: {
        type: Array,
        value: []
      },
      mainDataPath: String
    },

    _computeAvailableCpOutputs: function(cpOutputs, alreadySelectedCpOutputs, selectedCpStructure) {
      let selectedCpStructureId = parseInt(selectedCpStructure, 10);
      return cpOutputs.filter(function(cp) {
        let notSelected = alreadySelectedCpOutputs.indexOf(cp.id) === -1;
        let belongsToCpStructure = true;
        if (selectedCpStructureId > 0 && selectedCpStructureId !== parseInt(cp.country_programme, 10)) {
          belongsToCpStructure = false;
        }
        return notSelected && belongsToCpStructure;
      });
    },

    setAlreadySelectedCpOutputs: function(resultsLength, results) {
      if (resultsLength > 0) {
        this.set('alreadySelectedCpOutputs', this._getSelectedCpOutputsIds(results || []));
      } else {
        this.set('alreadySelectedCpOutputs', []);
      }
    },

    // get selected cpoutputs ids
    _getSelectedCpOutputsIds: function(results) {
      let selectedCpOIds = [];
      if (results.length > 0) {
        results.forEach(function(result) {
          if (result.cp_output) {
            selectedCpOIds.push(result.cp_output);
          }
        });
      }
      return selectedCpOIds;
    },

    removeCpOutputRamIndicatorsDialog: function() {
      if (this.cpOutputRamIndicatorsEditElem) {
        Polymer.dom(document.querySelector('body')).removeChild(this.cpOutputRamIndicatorsEditElem);
      }
    },

    createAddEditCpOutputRamIndicatorsElement: function() {
      this.cpOutputRamIndicatorsEditElem = Polymer.dom(document.querySelector('body'))
          .querySelector('#cpOutputRamIndicatorsEditElem');
      if (!this.cpOutputRamIndicatorsEditElem) {
        this.cpOutputRamIndicatorsEditElem = document.createElement('result-cp-output-and-ram-indicators');
        this.cpOutputRamIndicatorsEditElem.setAttribute('id', 'cpOutputRamIndicatorsEditElem');

        this.cpOutputRamIndicatorsEditElem.set('toastEventSource', this);

        this.cpOutputRamIndicatorsEditElem.addEventListener('new-expected-result-added',
            this._handleNewResultAdded.bind(this));

        this.cpOutputRamIndicatorsEditElem.addEventListener('expected-result-updated',
            this._handleResultUpdated.bind(this));

        Polymer.dom(document.querySelector('body')).appendChild(this.cpOutputRamIndicatorsEditElem);
      }
    },

    openCpOutputAndRamIndicatorsDialog: function(expectedResultId, cpOutputId, ramIndicatorsIds, editIndex) {
      if (this.cpOutputRamIndicatorsEditElem) {
        this.cpOutputRamIndicatorsEditElem.resetData();

        this.cpOutputRamIndicatorsEditElem.set('interventionId', this.interventionId);
        this.cpOutputRamIndicatorsEditElem.set('expectedResultId', expectedResultId);
        this.cpOutputRamIndicatorsEditElem.set('selectedRamIndicatorsIds', ramIndicatorsIds);

        let availableCpOutputsOptions = this.availableCpOutputs.slice(0);
        if (cpOutputId) {
          /**
           * cpOutputId is valid => edit operation, include curent cpOutput in the availableCpOutputsOptions
           * as user might want to edit only the ram indicators
           */
          let currentCpOutputData = this.cpOutputs.find(function(cp) {
            return parseInt(cp.id, 10) === parseInt(cpOutputId, 10);
          });
          if (currentCpOutputData) {
            availableCpOutputsOptions.push(currentCpOutputData);
          } // else => old cp output, not found, it's data will be requested by the cp outputs dropdown

          // prevent ram indicators reset at first request, edit operation
          this.cpOutputRamIndicatorsEditElem.set('_preventRamIndicatorReset', true);
          this.cpOutputRamIndicatorsEditElem.set('editIndex', editIndex);
        }
        this.cpOutputRamIndicatorsEditElem.set('availableCpOutputs', availableCpOutputsOptions);
        this.cpOutputRamIndicatorsEditElem.set('selectedCpOutputId', cpOutputId);

        this.cpOutputRamIndicatorsEditElem.openDialog();
      }
    },

    _handleNewResultAdded: function(e) {
      e.stopImmediatePropagation();
      if (!this._canUpdateResult()) {
        return;
      }
      let resultLink = e.detail.result;
      this._initializeToBeAbleToAddLowerResult(resultLink);

      this.push('dataItems', resultLink);
    },
    _initializeToBeAbleToAddLowerResult: function(resultLink) {
      if (!resultLink.ll_results) {
        resultLink.ll_results = [];
      }
    },
    _handleResultUpdated: function(e) {
      e.stopImmediatePropagation();
      if (!this._canUpdateResult()) {
        return;
      }
      this.set(['dataItems', e.detail.index, 'cp_output'], e.detail.result.cp_output);
      this.set(['dataItems', e.detail.index, 'ram_indicators'], e.detail.result.ram_indicators);
    },

    _canUpdateResult: function() {
      if (!this.get('dataItems')) {
        this.logError('dataItems is undefined or null. You must have dataItems(Array of result_links) defined ' +
            'to use this behavior.', 'results-behavior');
        return false;
      }
      return true;
    }

  };

  /** @polymerBehavior EtoolsPmpApp.Behaviors.ExpectedResults */
  EtoolsPmpApp.Behaviors.ExpectedResults = [
    EtoolsLogsBehavior,
    EtoolsPmpApp.Behaviors.EtoolsDataReduxStore,
    EtoolsPmpApp.Behaviors.ExpectedResultsImpl
  ]
</script>

{'fraction_non_alphanumeric': 0.10901613904407201, 'fraction_numerical': 0.0020173805090006208, 'mean_word_length': 3.167151632719043, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6205787', 'n_tokens_mistral': 3859, 'n_tokens_neox': 3731, 'n_words': 596}