<commit_before>import React from 'react';
import _ from 'underscore';

import {Actions,
  AccountStore,
  MailRulesStore,
  MailRulesTemplates,
  TaskQueueStatusStore,
  ReprocessMailRulesTask} from 'nylas-exports';

import {Flexbox,
  EditableList,
  RetinaImg,
  ScrollRegion,
  ScenarioEditor} from 'nylas-component-kit';

const {
  ActionTemplatesForAccount,
  ConditionTemplatesForAccount,
} = MailRulesTemplates;


class PreferencesMailRules extends React.Component {
  static displayName = 'PreferencesMailRules';

  constructor() {
    super();
    this.state = this._getStateFromStores();
  }

  componentDidMount() {
    this._unsubscribers = [];
    this._unsubscribers.push(MailRulesStore.listen(this._onRulesChanged));
    this._unsubscribers.push(TaskQueueStatusStore.listen(this._onTasksChanged));
  }

  componentWillUnmount() {
    this._unsubscribers.forEach(unsubscribe => unsubscribe());
  }

  _getStateFromStores() {
    const accounts = AccountStore.accounts();
    const state = this.state || {};
    let {currentAccount} = state;
    if (!accounts.find(acct => acct === currentAccount)) {
      currentAccount = accounts[0];
    }
    const rules = MailRulesStore.rulesForAccountId(currentAccount.accountId);
    const selectedRule = this.state && this.state.selectedRule ? _.findWhere(rules, {id: this.state.selectedRule.id}) : rules[0];

    return {
      accounts: accounts,
      currentAccount: currentAccount,
      rules: rules,
      selectedRule: selectedRule,
      tasks: TaskQueueStatusStore.tasksMatching(ReprocessMailRulesTask, {}),
      actionTemplates: ActionTemplatesForAccount(currentAccount),
      conditionTemplates: ConditionTemplatesForAccount(currentAccount),
    }
  }

  _onSelectAccount = (event) => {
    const accountId = event.target.value;
    const currentAccount = this.state.accounts.find(acct => acct.accountId === accountId);
    this.setState({currentAccount: currentAccount}, () => {
      this.setState(this._getStateFromStores())
    });
  }

  _onReprocessRules = () => {
    const needsMessageBodies = () => {
      for (const rule of this.state.rules) {
        for (const condition of rule.conditions) {
          if (condition.templateKey === 'body') {
            return true;
          }
        }
      }
      return false;
    }

    if (needsMessageBodies()) {
      NylasEnv.showErrorDialog("One or more of your mail rules requires the bodies of messages being processed. These rules can't be run on your entire mailbox.");
    }

    const task = new ReprocessMailRulesTask(this.state.currentAccount.accountId)
    Actions.queueTask(task);
  }

  _onAddRule = () => {
    Actions.addMailRule({accountId: this.state.currentAccount.accountId});
  }

  _onSelectRule = (rule) => {
    this.setState({selectedRule: rule});
  }

  _onReorderRule = (rule, startIdx, endIdx) => {
    Actions.reorderMailRule(rule.id, endIdx);
  }

  _onDeleteRule = (rule) => {
    Actions.deleteMailRule(rule.id);
  }

  _onRuleNameEdited = (newName, rule) => {
    Actions.updateMailRule(rule.id, {name: newName});
  }

  _onRuleConditionModeEdited = (event) => {
    Actions.updateMailRule(this.state.selectedRule.id, {conditionMode: event.target.value});
  }

  _onRuleEnabled = () => {
    Actions.updateMailRule(this.state.selectedRule.id, {disabled: false, disabledReason: null});
  }

  _onRulesChanged = () => {
    const next = this._getStateFromStores();
    const nextRules = next.rules;
    const prevRules = this.state.rules ? this.state.rules : [];

    const added = _.difference(nextRules, prevRules);
    if (added.length === 1) {
      next.selectedRule = added[0];
    }

    this.setState(next);
  }

  _onTasksChanged = () => {
    this.setState({tasks: TaskQueueStatusStore.tasksMatching(ReprocessMailRulesTask, {})})
  }

  _renderAccountPicker() {
    const options = this.state.accounts.map(account =>
      <option value={account.accountId} key={account.accountId}>{account.label}</option>
    );

    return (
      <select
        value={this.state.currentAccount.accountId}
        onChange={this._onSelectAccount}
        style={{margin: 0, minWidth: 200}}
      >
        {options}
      </select>
    );
  }

  _renderMailRules() {
    if (this.state.rules.length === 0) {
      return (
        <div className="empty-list"><commit_msg>fix(mail-rules): use the right field name to get an account id<commit_after>import React from 'react';
import _ from 'underscore';

import {Actions,
  AccountStore,
  MailRulesStore,
  MailRulesTemplates,
  TaskQueueStatusStore,
  ReprocessMailRulesTask} from 'nylas-exports';

import {Flexbox,
  EditableList,
  RetinaImg,
  ScrollRegion,
  ScenarioEditor} from 'nylas-component-kit';

const {
  ActionTemplatesForAccount,
  ConditionTemplatesForAccount,
} = MailRulesTemplates;


class PreferencesMailRules extends React.Component {
  static displayName = 'PreferencesMailRules';

  constructor() {
    super();
    this.state = this._getStateFromStores();
  }

  componentDidMount() {
    this._unsubscribers = [];
    this._unsubscribers.push(MailRulesStore.listen(this._onRulesChanged));
    this._unsubscribers.push(TaskQueueStatusStore.listen(this._onTasksChanged));
  }

  componentWillUnmount() {
    this._unsubscribers.forEach(unsubscribe => unsubscribe());
  }

  _getStateFromStores() {
    const accounts = AccountStore.accounts();
    const state = this.state || {};
    let {currentAccount} = state;
    if (!accounts.find(acct => acct === currentAccount)) {
      currentAccount = accounts[0];
    }
    const rules = MailRulesStore.rulesForAccountId(currentAccount.id);
    const selectedRule = this.state && this.state.selectedRule ? _.findWhere(rules, {id: this.state.selectedRule.id}) : rules[0];

    return {
      accounts: accounts,
      currentAccount: currentAccount,
      rules: rules,
      selectedRule: selectedRule,
      tasks: TaskQueueStatusStore.tasksMatching(ReprocessMailRulesTask, {}),
      actionTemplates: ActionTemplatesForAccount(currentAccount),
      conditionTemplates: ConditionTemplatesForAccount(currentAccount),
    }
  }

  _onSelectAccount = (event) => {
    const accountId = event.target.value;
    const currentAccount = this.state.accounts.find(acct => acct.id === accountId);
    this.setState({currentAccount: currentAccount}, () => {
      this.setState(this._getStateFromStores())
    });
  }

  _onReprocessRules = () => {
    const needsMessageBodies = () => {
      for (const rule of this.state.rules) {
        for (const condition of rule.conditions) {
          if (condition.templateKey === 'body') {
            return true;
          }
        }
      }
      return false;
    }

    if (needsMessageBodies()) {
      NylasEnv.showErrorDialog("One or more of your mail rules requires the bodies of messages being processed. These rules can't be run on your entire mailbox.");
    }

    const task = new ReprocessMailRulesTask(this.state.currentAccount.id)
    Actions.queueTask(task);
  }

  _onAddRule = () => {
    Actions.addMailRule({accountId: this.state.currentAccount.id});
  }

  _onSelectRule = (rule) => {
    this.setState({selectedRule: rule});
  }

  _onReorderRule = (rule, startIdx, endIdx) => {
    Actions.reorderMailRule(rule.id, endIdx);
  }

  _onDeleteRule = (rule) => {
    Actions.deleteMailRule(rule.id);
  }

  _onRuleNameEdited = (newName, rule) => {
    Actions.updateMailRule(rule.id, {name: newName});
  }

  _onRuleConditionModeEdited = (event) => {
    Actions.updateMailRule(this.state.selectedRule.id, {conditionMode: event.target.value});
  }

  _onRuleEnabled = () => {
    Actions.updateMailRule(this.state.selectedRule.id, {disabled: false, disabledReason: null});
  }

  _onRulesChanged = () => {
    const next = this._getStateFromStores();
    const nextRules = next.rules;
    const prevRules = this.state.rules ? this.state.rules : [];

    const added = _.difference(nextRules, prevRules);
    if (added.length === 1) {
      next.selectedRule = added[0];
    }

    this.setState(next);
  }

  _onTasksChanged = () => {
    this.setState({tasks: TaskQueueStatusStore.tasksMatching(ReprocessMailRulesTask, {})})
  }

  _renderAccountPicker() {
    const options = this.state.accounts.map(account =>
      <option value={account.id} key={account.id}>{account.label}</option>
    );

    return (
      <select
        value={this.state.currentAccount.id}
        onChange={this._onSelectAccount}
        style={{margin: 0, minWidth: 200}}
      >
        {options}
      </select>
    );
  }

  _renderMailRules() {
    if (this.state.rules.length === 0) {
      return (
        <div className="empty-list">
{'fraction_non_alphanumeric': 0.1276300578034682, 'fraction_numerical': 0.0020809248554913293, 'mean_word_length': 3.46849173553719, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 47, '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': '6614433', 'n_tokens_mistral': 2706, 'n_tokens_neox': 2629, 'n_words': 473}