<template>
  <div :class="{ 'c-input-password--has-rule-helper': enableRulesHelper }">
    <el-input
      :class="{ 'l-flex-grid--no-wrap': enableRulesHelper }"
      :type="!togglePassword ? 'password' : 'text'"
      :placeholder="placeholder"
      :value="value"
      v-test-id="'input-password'"
      @input="$emit('input', $event)"
      @focus="updateInputFocus(true, 'focus', $event)"
      @blur="updateInputFocus(false, 'blur', $event)"
      @change="$emit('change', $event)">
      <div slot="append">
        <label>
          <el-checkbox
            v-model="togglePassword"
            v-test-id="'show-password'"></el-checkbox>
          <span class="u-ml1">Show</span>
        </label>
      </div>
    </el-input>
    <el-collapse-transition v-if="enableRulesHelper">
      <div v-show="inputHasFocus">
        <password-rules-helper
          ref="passwordRules"
          v-test-id="'rules-helper'"
          :value="value"
          :policy="policy"
          :store="store"
          :get-policy-action-name="getPolicyActionName">
        </password-rules-helper>
      </div>
    </el-collapse-transition>
  </div>

</template>

<script>
  import PasswordRulesHelper from './PasswordRulesHelper';

  export default {
    name: 'ElInputPassword',
    components: {PasswordRulesHelper},
    props: {
      passwordHidden: {
        type: Boolean,
        default: true
      },
      value: {
        type: String,
        required: true
      },
      placeholder: {
        type: String,
        default: ''
      },
      enableRulesHelper: {
        type: Boolean,
        default: false
      },
      // Policy can have the following attributes:
      // { MinimumLength: 8, RequireLowercase: true, RequireNumbers: true, RequireSymbols: true, RequireUppercase: true, DisallowLeadingAndTrailingSpaces: true }
      policy: {
        type: Object
      },
      store: {
        type: Object
      },
      getPolicyActionName: {
        type: String,
        required: false
      }
    },
    data: function() {
      return {
        togglePassword: !this.passwordHidden,
        inputHasFocus: false
      };
    },
    methods: {
      updateInputFocus: function(isFocused, type, event) {
        this.inputHasFocus = isFocused;
        this.$emit(type, event);
        if (isFocused && this.enableRulesHelper) {
          this.$refs.passwordRules.refreshPolicyAndValidation();
        }
      }
    }
  };
</script>
