<template>
  <v-dialog v-model="dialog" :disabled="disabled" content-class="uiPopup" 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-progress-circular>
        <v-spacer />
      </v-card-title>
      <v-card-text>
        <div v-if="errorMessage" class="alert alert-error">
          <i class="uiIconError"></i>
          {{ errorMessage }}
        </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">
          <v-text-field
            v-if="!autoGeneratedPassword"
            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
            @click:append="walletPasswordShow = !walletPasswordShow"
          />

          <v-text-field
            v-if="!rememberPasswordToChange"
            v-model="newWalletPassword"
            :append-icon="newWalletPasswordShow ? 'visibility_off' : 'visibility'"
            :rules="[rules.min]"
            :type="newWalletPasswordShow ? 'text' : 'password'"
            :disabled="loading"
            name="newWalletPassword"
            label="New wallet password"
            placeholder="Enter your new wallet password"
            counter
            @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="loading =true; 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';

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,
      errorMessage: 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.errorMessage = 'Can\'t reset wallet because it doesn\'t exist in current browser';
        }
      } 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.errorMessage = 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.errorMessage = null;
      this.loading = true;
      // Check if original password is ok
      const unlocked = unlockBrowerWallet(this.autoGeneratedPassword ? window.walletSettings.userP : hashCode(this.walletPassword));
      if (unlocked) {
        try {
          if (this.rememberPasswordToChange) {
            rememberPassword(true, hashCode(this.walletPassword));
          } else {
            saveBrowerWallet(this.newWalletPassword, null, null, false, this.rememberPassword);
            this.$emit("reseted");
          }
          this.loading = false;
          this.dialog = false;
        } catch (e) {
          this.loading = false;
          console.debug("saveWallet method error", e);
          this.errorMessage = String(e);
          return;
        }
      } else {
        this.loading = false;
        this.errorMessage = 'Wrong password';
      }
    }
  }
};
</script>