<template>
  <v-list density="compact" @click.stop="nullEvent" color="primary">
      <v-list-item
        v-for="device in devices"
        :key="device.deviceId"
        :value="device.deviceId"
      >
        <template v-slot:default>
            <v-list-item-title>{{ displayName(device) }}</v-list-item-title>
            <v-list-item-subtitle>{{
              verificationStatus(device)
            }}</v-list-item-subtitle>
        </template>
        <template v-slot:append="{ isActive }">
          <v-list-item-action v-if="isActive">
            <v-btn icon>
              <v-icon
                :color="
                  device.isBlocked
                    ? 'red'
                    : device.isVerified
                    ? 'green'
                    : 'grey-lighten-1'
                "
                >verified_user</v-icon
              >
            </v-btn>
          </v-list-item-action>
        </template>
      </v-list-item>
  </v-list>
</template>

<script>
import { DeviceVerification } from 'matrix-js-sdk';

export default {
  name: "DeviceList",
  props: {
    member: {
      type: Object,
      default: function () {
        return {};
      },
    },
  },
  data() {
    return {
      devices: [],
    };
  },
  watch: {
    member: {
      immediate: true,
      handler(member, ignoredOldVal) {
        this.updateDevices();
        if (member) {
          this.$matrix.matrixClient.downloadKeysForUsers([member.userId]).then(() => {
            this.updateDevices();
          });
        }
      },
    },
  },
  methods: {
    updateDevices() {
      if (!this.member) {
        this.devices = [];
        return;
      }
      this.$matrix.matrixClient.getCrypto().getUserDeviceInfo(
        [this.member.userId], true
      ).then(deviceMap => {
        if (deviceMap && deviceMap.get(this.member.userId)) {
          const userDevices = deviceMap.get(this.member.userId);
          const devices = [...userDevices.keys()].map(k => {
            return userDevices.get(k);
          }).map(d => ({
              deviceId: d.deviceId,
              displayName: d.displayName,
              isBlocked: d.verified == DeviceVerification.Blocked,
              isVerified: d.verified == DeviceVerification.Verified
            }));
          this.devices = devices;
        }
      })
    },

    displayName(device) {
      var name = device.deviceId;
      if (device.displayName) {
        name += " - " + device.displayName;
      }
      return name;
    },

    verificationStatus(device) {
      if (device.isBlocked) {
        return this.$t('device_list.blocked');
      } else if (device.isVerified) {
        return this.$t('device_list.verified');
      } else {
        return this.$t('device_list.not_verified');
      }
    },

    nullEvent() {},
  },
};
</script>
