<template>
  <v-flex id="walletSetup" class="text-xs-center">
    <div v-if="displayWalletBackup" class="alert alert-warning">
      <i class="uiIconWarning"></i>
      Your wallet is not backed up yet.
      <wallet-backup-modal display-complete-message @copied="hideBackupMessage()" />
      <a href="javascript:void(0);" @click="skipWalletBackedUp">Don't ask me again</a>
    </div>

    <div v-if="displayResetPassword" class="alert alert-warning">
      <i class="uiIconWarning"></i>
      Your wallet is not secured yet.
      <wallet-reset-modal button-label="Set a password" @reseted="hideSetPasswordMessage();$emit('refresh');"/>
      <a href="javascript:void(0);" @click="hideSetPasswordMessage">Don't ask me again</a>
    </div>

    <div v-if="displayWalletCreationToolbar" class="alert alert-info">
      <i class="uiIconInfo"></i>
      No private key was found in current browser. Your wallet is displayed in readonly mode.
      <a v-if="!displayWalletSetup" href="javascript:void(0);" @click="displayWalletSetupActions()">More options</a>
    </div>

    <div v-if="displayWalletNotExistingYet" class="alert alert-info">
      <i class="uiIconInfo"></i>
      Space administrator hasn't set a Wallet for this space yet
    </div>
    <wallet-metamask-setup
      v-else-if="useMetamask"
      ref="walletMetamaskSetup"
      :is-space="isSpace"
      :is-space-administrator="isSpaceAdministrator"
      :wallet-address="walletAddress"
      :refresh-index="refreshIndex"
      @loading="$emit('loading')"
      @refresh="refresh()"
      @end-loading="$emit('end-loading')"
      @error="$emit('error', $event)" />
    <wallet-browser-setup
      v-else-if="displayWalletSetup"
      ref="walletBrowserSetup"
      :is-space="isSpace"
      :is-space-administrator="isSpaceAdministrator"
      :refresh-index="refreshIndex"
      @configured="refresh()"
      @loading="$emit('loading')"
      @end-loading="$emit('end-loading')"
      @error="$emit('error', $event)" />
  </v-flex>
</template>

<script>
import WalletBrowserSetup from './WalletBrowserSetup.vue';
import WalletMetamaskSetup from './WalletMetamaskSetup.vue';
import WalletBackupModal from './WalletBackupModal.vue';
import WalletResetModal from './WalletResetModal.vue';

import {setWalletBackedUp, skipWalletPasswordSet, skipWalletBackedUp} from '../WalletUtils.js';

export default {
  components: {
    WalletBrowserSetup,
    WalletMetamaskSetup,
    WalletResetModal,
    WalletBackupModal
  },
  props: {
    isSpace: {
      type: Boolean,
      default: function() {
        return false;
      }
    },
    isSpaceAdministrator: {
      type: Boolean,
      default: function() {
        return false;
      }
    },
    isReadOnly: {
      type: Boolean,
      default: function() {
        return false;
      }
    },
    walletAddress: {
      type: String,
      default: function() {
        return null;
      }
    },
    refreshIndex: {
      type: Number,
      default: function() {
        return 0;
      }
    }
  },
  data() {
    return {
      useMetamask: false,
      autoGenerated: false,
      skipWalletPasswordSet: false,
      browserWalletExists: false,
      displayWalletSetup: false,
      networkId: null,
      browserWalletBackedUp: true,
      watchMetamaskAccountInterval: null,
      detectedMetamaskAccount: null
    };
  },
  computed: {
    displayWalletNotExistingYet() {
      return this.isSpace && !this.isSpaceAdministrator && !this.walletAddress;
    },
    displayWalletCreationToolbar() {
      return this.walletAddress && !this.useMetamask && !this.browserWalletExists && this.isReadOnly && (!this.isSpace || this.isSpaceAdministrator);
    },
    displayWalletBackup() {
      return this.walletAddress && !this.useMetamask && this.browserWalletExists && !this.browserWalletBackedUp;
    },
    displayResetPassword() {
      return this.walletAddress && !this.useMetamask && this.browserWalletExists && !this.skipWalletPasswordSet && this.autoGenerated;
    }
  },
  watch: {
    refreshIndex(newValue, oldValue) {
      if (newValue > oldValue) {
        this.init();
      }
    }
  },
  created() {
    this.init();
  },
  methods: {
    refresh() {
      console.log("refresh");
      this.$emit("refresh");
    },
    init() {
      this.isReadOnly = window.walletSettings.isReadOnly;
      this.browserWalletExists = window.walletSettings.browserWalletExists;
      this.useMetamask = window.walletSettings.userPreferences.useMetamask;
      this.isSpaceAdministrator = window.walletSettings.isSpaceAdministrator;
      this.browserWalletBackedUp = window.walletSettings.userPreferences.backedUp || window.walletSettings.userPreferences.skipBackup;
      this.autoGenerated = window.walletSettings.userPreferences.autoGenerated;
      this.skipWalletPasswordSet = window.walletSettings.userPreferences.skipWalletPasswordSet;

      this.displayWalletSetup = !this.walletAddress && (!this.isSpace || this.isSpaceAdministrator);

      if (this.useMetamask) {
        this.detectedMetamaskAccount = window.walletSettings.detectedMetamaskAccount;
        this.watchMetamaskAccount();
      }
    },
    displayWalletSetupActions() {
      this.displayWalletSetup = true;
    },
    hideSetPasswordMessage() {
      skipWalletPasswordSet();
      this.skipWalletPasswordSet = true;
    },
    hideBackupMessage() {
      setWalletBackedUp(null, true);
      this.browserWalletBackedUp = true;
    },
    skipWalletBackedUp() {
      skipWalletBackedUp();
      this.browserWalletBackedUp = true;
    },
    watchMetamaskAccount() {
      const thiss = this;

      if (this.watchMetamaskAccountInterval) {
        clearInterval(this.watchMetamaskAccountInterval);
      }
      // In case account switched in Metamask
      // See https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md
      this.watchMetamaskAccountInterval = setInterval(function() {
        if (!thiss.useMetamask || !thiss.detectedMetamaskAccount || !window || !window.ethereum) {
          return;
        }

        window.ethereum.enable()
          .then(accounts => {
            window.walletSettings.detectedMetamaskAccount = accounts && accounts.length ? accounts[0].toLowerCase() : null;
            if (window.walletSettings.detectedMetamaskAccount && window.walletSettings.detectedMetamaskAccount.toLowerCase() !== thiss.detectedMetamaskAccount) {
              thiss.$emit('refresh');
              return;
            }
          });
      }, 2000);
    }
  }
};
</script>