<template>
  <div>
    <div class="row-wrapper">
      <div>
        <button class="icon" @click="$emit('edit-environment')">
          <i class="material-icons">layers</i>
          <span>{{ environment.name }}</span>
        </button>
      </div>
      <v-popover>
        <button v-tooltip.left="$t('more')" class="tooltip-target icon">
          <i class="material-icons">more_vert</i>
        </button>
        <template slot="popover">
          <div>
            <button
              v-close-popover
              class="icon"
              @click="$emit('edit-environment')"
            >
              <i class="material-icons">create</i>
              <span>{{ $t("edit") }}</span>
            </button>
          </div>
          <div>
            <button v-close-popover class="icon" @click="confirmRemove = true">
              <i class="material-icons">delete</i>
              <span>{{ $t("delete") }}</span>
            </button>
          </div>
        </template>
      </v-popover>
    </div>
    <SmartConfirmModal
      :show="confirmRemove"
      :title="$t('are_you_sure_remove_environment')"
      @hide-modal="confirmRemove = false"
      @resolve="removeEnvironment"
    />
  </div>
</template>

<script>
import { fb } from "~/helpers/fb"
import { getSettingSubject } from "~/newstore/settings"

export default {
  props: {
    environment: { type: Object, default: () => {} },
    environmentIndex: { type: Number, default: null },
  },
  data() {
    return {
      confirmRemove: false,
    }
  },
  subscriptions() {
    return {
      SYNC_ENVIRONMENTS: getSettingSubject("syncEnvironments"),
    }
  },
  methods: {
    syncEnvironments() {
      if (fb.currentUser !== null && this.SYNC_ENVIRONMENTS) {
        fb.writeEnvironments(
          JSON.parse(JSON.stringify(this.$store.state.postwoman.environments))
        )
      }
    },
    removeEnvironment() {
      this.$store.commit("postwoman/removeEnvironment", this.environmentIndex)
      this.$toast.error(this.$t("deleted"), {
        icon: "delete",
      })
      this.syncEnvironments()
    },
  },
}
</script>
