<template>
  <div>
    <ul class="u-list-unstyled u-mb0">
      <li
        v-for="rule in rules"
        :key="rule.name"
        class="u-mb0">
        <small :class="{'u-text--info': !rule.valid, 'u-text--success': rule.valid}">
          <fa-icon
            v-if="rule.valid"
            icon="check"
            size="sm"/>
          <fa-icon
            v-else
            icon="exclamation-circle"/>
          {{ rule.text }}
        </small>
      </li>
    </ul>
  </div>
</template>

<script>
import PasswordValidator from 'main/utils/validators/PasswordValidator';

export default {
  props: {
    value: { type: String, required: true },
    policy: { type: Object, required: false },
    store: { type: Object, required: false },
    getPolicyActionName: { type: String, required: false }
  },
  data: function() {
    return {
      rules: [],
      passwordValidator: null
    };
  },
  created: function() {
    this.passwordValidator = new PasswordValidator({ policy: this.policy, store: this.store, getPolicyActionName: this.getPolicyActionName });
    this.refreshValidation();
  },
  methods: {
    refreshPolicyAndValidation: async function() {
      await this.passwordValidator.refreshPolicy();
      this.refreshValidation();
    },
    refreshValidation: async function() {
      const validationResult = await this.passwordValidator.testPasswordAgainstPolicy(this.value);

      this.rules = validationResult.results.map(ruleTestResult => {
        return {
          valid: ruleTestResult.passed,
          text: ruleTestResult.message
        };
      });
    }
  },
  watch: {
    value: function(oldValue, newValue) {
      this.refreshValidation();
    }
  }
};
</script>
