<commit_before>import Ember from 'ember';
import NewOrEdit from 'ui/mixins/new-or-edit';
import ShellQuote from 'npm:shell-quote';
import C from 'ui/utils/constants';

export default Ember.Component.extend(NewOrEdit, {
  k8s: Ember.inject.service(),
  projects: Ember.inject.service(),

  allTemplates: null,
  templateResource: null,
  environmentResource: null,
  versionsArray: null,
  versionsLinks: null,
  serviceChoices: null,
  templateBase: null,

  classNames: ['launch-catalog'],

  primaryResource: Ember.computed.alias('environmentResource'),
  editing: false,

  previewOpen: false,
  previewTab: null,
  questionsArray: null,
  selectedTemplateUrl: null,
  selectedTemplateModel: null,
  readmeContent: null,

  actions: {
    cancel: function() {
      this.sendAction('cancel');
    },

    togglePreview: function() {
      this.toggleProperty('previewOpen');
    },

    selectPreviewTab: function(tab) {
      this.set('previewTab', tab);
    },

    changeTemplate: function(tpl) {
      this.get('application').transitionToRoute('catalog-tab.launch', tpl.id);
    },
  },

  didReceiveAttrs() {
    this._super();

    this.set('editing', !!this.get('primaryResource.id'));

    // Select the default version
    var def = this.get('templateResource.defaultVersion');
    var links = this.get('versionLinks');
    if (links[def]) {
      this.set('selectedTemplateUrl', links[def]);
    } else {
      this.set('selectedTemplateUrl', null);
    }
  },

  getReadme: function() {
    this.get('selectedTemplateModel').followLink('readme').then((response) => {
      this.set('readmeContent', response);
    });
  },

  templateChanged: function() {
    var link = this.get('selectedTemplateUrl');
    if (link) {
      this.set('loading', true);

      var current = this.get('environmentResource.environment');
      this.get('store').request({
        url: link
      }).then((response) => {
        if (response.questions) {
          response.questions.forEach((item) => {
            // This will be the component that is rendered to edit this answer
            item.inputComponent = 'schema/input-'+item.type;

            // Only types marked supported will show the component, Ember will explode if the component doesn't exist
            item.supported = C.SUPPORTED_SCHEMA_INPUTS.indexOf(item.type) >= 0;

            if (typeof current[item.variable] !== 'undefined') {
              // If there's an existing value, use it (for upgrade)
              item.answer = current[item.variable];
            } else if (item.type === 'service' || item.type === 'certificate') {
                // Loaded async and then the component picks the default
            } else if ( item.type === 'boolean' ) {
              // Coerce booleans
              item.answer = (item.default === 'true' || item.default === true);
            } else {
              // Everything else
              item.answer = item.default;
            }
          });
        }

        this.set('selectedTemplateModel', response);
        this.set('previewTab', Object.keys(response.get('files')||[])[0]);
        if (response.links.readme) {
          this.getReadme();
        } else {
          this.set('readmeContent', null);
        }
        this.set('loading', false);
      }, ( /*error*/ ) => {});
    } else {
      this.set('selectedTemplateModel', null);
    }
  }.observes('selectedTemplateUrl').on('init'),

  answers: function() {
    var out = {};
    (this.get('selectedTemplateModel.questions') || []).forEach((item) => {
      out[item.variable] = item.answer;
    });

    return out;
  }.property('selectedTemplateModel.questions.@each.{variable,answer}'),

  answersArray: Ember.computed.alias('selectedTemplateModel.questions'),

  answersString: function() {
    return (this.get('answersArray')||[]).map((obj) => {
      if (obj.answer === null || obj.answer === undefined) {
        return obj.variable + '=';
      } else {
        return obj.variable + '=' + ShellQuote.quote([obj.answer]);
      }
    }).join("\n");
  }.property('answersArray.@each.{variable,answer}'),

  validate() {
    var errors = [];

    if (!this.get('editing') && !this.get('environmentResource.name')) {
      errors.push('Name is required');
    }

    if (this.get('selectedTemplateModel.questions')) {
      this.get('selectedTemplateModel.questions').forEach((item) => {
        if (item.required && item.type !== 'boolean' && !item.answer) {
          errors.push(`${item.label} is required`);
        }
      });
    }

    if (errors.length) {
      this.set('errors', errors.uniq());
      this.$().parent().scrollTop(0);
      return false;
    }

    return true;
  },

  newExternalId: function() {
    var externalId = ( this.get('isSystem') ? C.EXTERNALID.KIND_SYSTEM_CATALOG : C.EXTERNALID.KIND_CATALOG );
    externalId += C.EXTERNALID.KIND_SEPARATOR + this.get('selectedTemplateModel.id');
    return externalId;
  }.property('isSystem','selectedTemplateModel.id'),

  isSystem: function() {
    var systemCategories = C.EXTERNALID.SYSTEM_CATEGORIES.map((str) => { return str.trim().toLowerCase(); });
    var category = (this.get('templateResource.category')||'').trim().toLowerCase();
    return systemCategories.indexOf(category) >= 0;
  }.property('templateResource.category'),

  willSave() {
    this.set('errors', null);
    var ok = this.validate();
    if (!ok) {
      // Validation failed
      return false;
    }

    var files = this.get('selectedTemplateModel.files');

    this.get('environmentResource').setProperties({
      dockerCompose: files['docker-compose.yml'],
      rancherCompose: files['rancher-compose.yml'],
      environment: this.get('answers'),
      externalId: this.get('newExternalId'),
    });

    return true;
  },

  doSave() {
    if ( this.get('templateBase') === 'kubernetes' ) {
      return this.get('k8s').catalog(
        this.get('selectedTemplateModel.files'),
        this.get('environmentResource.environment')
      );
    } else if ( this.get('templateBase') === 'swarm' ) {
      var env = this.get('environmentResource');<commit_msg>Remember stack systemness, read isSystem (rancher/rancher#5009)<commit_after>import Ember from 'ember';
import NewOrEdit from 'ui/mixins/new-or-edit';
import ShellQuote from 'npm:shell-quote';
import C from 'ui/utils/constants';

export default Ember.Component.extend(NewOrEdit, {
  k8s: Ember.inject.service(),
  projects: Ember.inject.service(),

  allTemplates: null,
  templateResource: null,
  environmentResource: null,
  versionsArray: null,
  versionsLinks: null,
  serviceChoices: null,
  templateBase: null,

  classNames: ['launch-catalog'],

  primaryResource: Ember.computed.alias('environmentResource'),
  editing: false,

  previewOpen: false,
  previewTab: null,
  questionsArray: null,
  selectedTemplateUrl: null,
  selectedTemplateModel: null,
  readmeContent: null,

  actions: {
    cancel: function() {
      this.sendAction('cancel');
    },

    togglePreview: function() {
      this.toggleProperty('previewOpen');
    },

    selectPreviewTab: function(tab) {
      this.set('previewTab', tab);
    },

    changeTemplate: function(tpl) {
      this.get('application').transitionToRoute('catalog-tab.launch', tpl.id);
    },
  },

  didReceiveAttrs() {
    this._super();

    this.set('editing', !!this.get('primaryResource.id'));

    // Select the default version
    var def = this.get('templateResource.defaultVersion');
    var links = this.get('versionLinks');
    if (links[def]) {
      this.set('selectedTemplateUrl', links[def]);
    } else {
      this.set('selectedTemplateUrl', null);
    }
  },

  getReadme: function() {
    this.get('selectedTemplateModel').followLink('readme').then((response) => {
      this.set('readmeContent', response);
    });
  },

  templateChanged: function() {
    var link = this.get('selectedTemplateUrl');
    if (link) {
      this.set('loading', true);

      var current = this.get('environmentResource.environment');
      this.get('store').request({
        url: link
      }).then((response) => {
        if (response.questions) {
          response.questions.forEach((item) => {
            // This will be the component that is rendered to edit this answer
            item.inputComponent = 'schema/input-'+item.type;

            // Only types marked supported will show the component, Ember will explode if the component doesn't exist
            item.supported = C.SUPPORTED_SCHEMA_INPUTS.indexOf(item.type) >= 0;

            if (typeof current[item.variable] !== 'undefined') {
              // If there's an existing value, use it (for upgrade)
              item.answer = current[item.variable];
            } else if (item.type === 'service' || item.type === 'certificate') {
                // Loaded async and then the component picks the default
            } else if ( item.type === 'boolean' ) {
              // Coerce booleans
              item.answer = (item.default === 'true' || item.default === true);
            } else {
              // Everything else
              item.answer = item.default;
            }
          });
        }

        this.set('selectedTemplateModel', response);
        this.set('previewTab', Object.keys(response.get('files')||[])[0]);
        if (response.links.readme) {
          this.getReadme();
        } else {
          this.set('readmeContent', null);
        }
        this.set('loading', false);
      }, ( /*error*/ ) => {});
    } else {
      this.set('selectedTemplateModel', null);
    }
  }.observes('selectedTemplateUrl').on('init'),

  answers: function() {
    var out = {};
    (this.get('selectedTemplateModel.questions') || []).forEach((item) => {
      out[item.variable] = item.answer;
    });

    return out;
  }.property('selectedTemplateModel.questions.@each.{variable,answer}'),

  answersArray: Ember.computed.alias('selectedTemplateModel.questions'),

  answersString: function() {
    return (this.get('answersArray')||[]).map((obj) => {
      if (obj.answer === null || obj.answer === undefined) {
        return obj.variable + '=';
      } else {
        return obj.variable + '=' + ShellQuote.quote([obj.answer]);
      }
    }).join("\n");
  }.property('answersArray.@each.{variable,answer}'),

  validate() {
    var errors = [];

    if (!this.get('editing') && !this.get('environmentResource.name')) {
      errors.push('Name is required');
    }

    if (this.get('selectedTemplateModel.questions')) {
      this.get('selectedTemplateModel.questions').forEach((item) => {
        if (item.required && item.type !== 'boolean' && !item.answer) {
          errors.push(`${item.label} is required`);
        }
      });
    }

    if (errors.length) {
      this.set('errors', errors.uniq());
      this.$().parent().scrollTop(0);
      return false;
    }

    return true;
  },

  newExternalId: function() {
    var externalId = ( this.get('isSystem') ? C.EXTERNALID.KIND_SYSTEM_CATALOG : C.EXTERNALID.KIND_CATALOG );
    externalId += C.EXTERNALID.KIND_SEPARATOR + this.get('selectedTemplateModel.id');
    return externalId;
  }.property('isSystem','selectedTemplateModel.id'),

  isSystem: function() {
    if ( this.get('editing') ) {
      return this.get('environmentResource.externalId').indexOf(C.EXTERNALID.KIND_SYSTEM_CATALOG + C.EXTERNALID.KIND_SEPARATOR) === 0;
    }

    let explicit = this.get('templateResource.isSystem');
    if ( explicit === true || explicit === false ) {
      return explicit;
    }

    let systemCategories = C.EXTERNALID.SYSTEM_CATEGORIES.map((str) => { return str.trim().toLowerCase(); });
    let category = (this.get('templateResource.category')||'').trim().toLowerCase();
    return systemCategories.indexOf(category) >= 0;
  }.property('editing','environmentResource.externalId','templateResource.{category,isSystem}'),

  willSave() {
    this.set('errors', null);
    var ok = this.validate();
    if (!ok) {
      // Validation failed
      return false;
    }

    var files = this.get('selectedTemplateModel.files');

    this.get('environmentResource').setProperties({
      dockerCompose: files['docker-compose.yml'],
      rancherCompose: files['rancher-compose.yml'],
      environment: this.get('answers'),
      externalId: this.get('newExternalId'),
    });

    return true;
  },

  doSave() {
    if ( this.get('templateBase') === 'kubernetes' ) {
      return this.get('k8s').catalog(
        this.get('selectedTemplateModel.files'),
        this.get('environmentResource.environment')
      );
    } else if ( this.get('templateBase') === 'swarm' ) {
      var env = this.get('environmentResource');
{'fraction_non_alphanumeric': 0.16173679215438153, 'fraction_numerical': 0.0013445112306232204, 'mean_word_length': 2.9270186335403725, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 23, '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': '6631996', 'n_tokens_mistral': 3793, 'n_tokens_neox': 3676, 'n_words': 696}