<template>
  <v-dialog
    v-model="dialog"
    :disabled="disabled"
    content-class="uiPopup with-overflow"
    class="walletResetModal"
    width="500px"
    max-width="100vw"
    persistent
    @keydown.esc="dialog = false">
    <div
      v-if="displayRememberMe"
      slot="activator"
      @click="
        $event.preventDefault();
        $event.stopPropagation();
      ">
      <template v-if="autoGeneratedPassword">
        <a href="javascript:void(0);" @click="dialog = true">
          Set your wallet password
        </a>
      </template>
      <template v-else>
        <a href="javascript:void(0);" @click="dialog = true">
          Reset your wallet password
        </a>
        <v-switch
          v-model="rememberPasswordStored"
          label="Remember password"
          @change="changeRememberMe" />
      </template>
    </div>
    <a
      v-else
      slot="activator"
      href="javascript:void(0);"
      @click="dialog = true">
      {{ buttonLabel }}
    </a>

    <v-card class="elevation-12">
      <div class="popupHeader ClearFix">
        <a
          class="uiIconClose pull-right"
          aria-hidden="true"
          @click="dialog = false"></a> <span class="PopupTitle popupTitle">
            {{ rememberPasswordToChange ? 'Password required' : autoGeneratedPassword ? 'Set wallet password' : 'Reset wallet password' }}
          </span>
      </div>
      <v-card-title v-show="loading" class="pb-0">
        <v-spacer />
        <v-progress-circular
          color="primary"
          indeterminate
          size="20" />
        <v-spacer />
      </v-card-title>
      <v-card-text>
        <div v-if="error" class="alert alert-error">
          <i class="uiIconError"></i> {{ error }}
        </div>

        <div v-if="!backedUp && !rememberPasswordToChange" class="alert alert-warning v-content">
          <i class="uiIconWarning"></i> It's highly recommended to backup your wallet before proceeding this operation
        </div>

        <v-form
          ref="form"
          @submit="
            $event.preventDefault();
            $event.stopPropagation();
          ">
          <v-text-field
            v-if="!autoGeneratedPassword && dialog"
            v-model="walletPassword"
            :append-icon="walletPasswordShow ? 'visibility_off' : 'visibility'"
            :rules="[rules.min]"
            :type="walletPasswordShow ? 'text' : 'password'"
            :disabled="loading"
            :label="rememberPasswordToChange ? 'Wallet password' : 'Current wallet password'"
            name="walletPassword"
            placeholder="Enter your wallet password"
            counter
            autocomplete="current-passord"
            autofocus
            @click:append="walletPasswordShow = !walletPasswordShow" />

          <v-text-field
            v-if="!rememberPasswordToChange && dialog"
            v-model="newWalletPassword"
            :append-icon="newWalletPasswordShow ? 'visibility_off' : 'visibility'"
            :rules="[rules.min]"
            :type="newWalletPasswordShow ? 'text' : 'password'"
            :disabled="loading"
            :autofocus="autoGeneratedPassword"
            name="newWalletPassword"
            label="New wallet password"
            placeholder="Enter your new wallet password"
            counter
            autocomplete="new-passord"
            @click:append="newWalletPasswordShow = !newWalletPasswordShow" />

          <v-switch
            v-if="autoGeneratedPassword"
            v-model="rememberPassword"
            label="Remember password" />
        </v-form>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <button
          :disabled="loading"
          class="btn btn-primary mr-1"
          @click="resetWallet()">
          Confirm
        </button> <button
          :disabled="loading"
          class="btn"
          @click="dialog = false">
          Close
        </button>
        <v-spacer />
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script>
import {unlockBrowerWallet, saveBrowerWallet, hashCode, rememberPassword} from '../WalletUtils.js';

import {setDraggable} from '../WalletUtils.js';

export default {
  props: {
    displayRememberMe: {
      type: Boolean,
      default: function() {
        return false;
      },
    },
    buttonLabel: {
      type: String,
      default: function() {
        return null;
      },
    },
  },
  data() {
    return {
      dialog: false,
      loading: false,
      backedUp: false,
      error: null,
      walletPassword: '',
      walletPasswordShow: false,
      newWalletPassword: '',
      newWalletPasswordShow: false,
      autoGeneratedPassword: false,
      browserWalletDecrypted: false,
      rememberPasswordStored: false,
      rememberPasswordToChange: false,
      rememberPassword: false,
      rules: {
        min: (v) => (v && v.length >= 8) || 'At least 8 characters',
      },
    };
  },
  watch: {
    dialog() {
      this.loading = true;
      if (this.dialog) {
        this.init();
        if (this.$refs.form) {
          this.$refs.form.reset();
        }
        if (!window.walletSettings.browserWalletExists) {
          this.error = "Can't reset wallet because it doesn't exist in current browser";
        }
        this.$nextTick(() => {
          setDraggable();
        });
      } else {
        if (this.rememberPasswordToChange) {
          this.rememberPasswordStored = window.walletSettings.storedPassword === true;
          this.rememberPasswordToChange = false;
        }
      }
      this.loading = false;
    },
  },
  created() {
    this.init();
    this.rememberPasswordStored = window.walletSettings.storedPassword;
  },
  methods: {
    init() {
      this.error = null;
      this.walletPassword = '';
      this.walletPasswordShow = false;
      this.newWalletPassword = '';
      this.newWalletPasswordShow = false;
      this.rememberPassword = false;
      this.autoGeneratedPassword = window.walletSettings.userPreferences.autoGenerated;
      this.backedUp = window.walletSettings.userPreferences.backedUp;
    },
    changeRememberMe() {
      if (this.loading || this.dialog) {
        return;
      }

      if (this.rememberPasswordStored) {
        this.rememberPasswordToChange = true;
        this.dialog = true;
      } else {
        rememberPassword(false);
      }
    },
    resetWallet() {
      this.error = null;
      if (!this.$refs.form.validate()) {
        return;
      }
      this.loading = true;
      const thiss = this;
      // Check if original password is ok
      window.setTimeout(() => {
        const unlocked = unlockBrowerWallet(thiss.autoGeneratedPassword ? window.walletSettings.userP : hashCode(thiss.walletPassword));
        if (unlocked) {
          try {
            if (thiss.rememberPasswordToChange) {
              rememberPassword(true, hashCode(thiss.walletPassword));
            } else {
              saveBrowerWallet(thiss.newWalletPassword, null, null, false, thiss.rememberPassword);
              thiss.$emit('reseted');
            }
            thiss.dialog = false;
            thiss.loading = false;
          } catch (e) {
            thiss.loading = false;
            console.debug('saveWallet method error', e);
            thiss.error = String(e);
            return;
          }
        } else {
          thiss.loading = false;
          thiss.error = 'Wrong password';
        }
      }, 200);
    },
  },
};
</script>
