<template>
  <li
    :class="{ 'hideable-element--greyed-out': hidden }"
    class="objective hideable-element"
    v-if="editMode || !hidden"
  >
    <visibility-action
      :block="objective"
      :type="type"
      v-if="editMode"
    />
    <div
      class="block-actions"
      v-if="editMode && canEdit"
    >
      <user-widget
        v-bind="me"
        class="block-actions__user-widget objective__user-widget"
      />
      <more-options-widget>
        <div class="popover-links__link">
          <a @click="deleteObjective(objective)">Löschen</a>
        </div>
      </more-options-widget>
    </div>
    <div>
      {{ objective.text }}
    </div>
  </li>
</template>

<script>
import VisibilityAction from '@/components/visibility/VisibilityAction.vue';
import UserWidget from '@/components/UserWidget.vue';
import MoreOptionsWidget from '@/components/MoreOptionsWidget.vue';

import DELETE_OBJECTIVE_MUTATION from '@/graphql/gql/mutations/deleteObjective.gql';
import MODULE_DETAILS_QUERY from '@/graphql/gql/queries/modules/moduleDetailsQuery.gql';
import { hidden } from '@/helpers/visibility';
import { OBJECTIVE_TYPE } from '@/consts/types';

import me from '@/mixins/me';

export default {
  props: {
    objective: {
      type: Object,
      default: null,
    },
    editMode: {
      type: Boolean,
      default: false,
    },
  },

  mixins: [me],

  components: {
    MoreOptionsWidget,
    VisibilityAction,
    UserWidget,
  },

  data() {
    return {
      type: OBJECTIVE_TYPE,
    };
  },

  computed: {
    hidden() {
      return hidden({
        block: this.objective,
        schoolClass: this.schoolClass,
        type: this.type,
      });
    },
    canEdit() {
      return this.objective.mine;
    },
  },

  methods: {
    deleteObjective(objective) {
      this.$apollo.mutate({
        mutation: DELETE_OBJECTIVE_MUTATION,
        variables: {
          input: {
            id: objective.id,
          },
        },
        refetchQueries: [
          {
            query: MODULE_DETAILS_QUERY,
            variables: {
              slug: this.$route.params.slug,
            },
          },
        ],
        // todo: make update work here also
        // update(store, {data: {deleteObjective: {success}}}) {
        //   if (success) {
        //     const query = MODULE_DETAILS_QUERY;
        //     const variables = {slug: this.$route.params.slug};
        //     const data = store.readQuery({query, variables});
        //     if (data) {
        //       data.module.objectiveGroups.edges.
        //       data.rooms.edges.splice(data.rooms.edges.findIndex(edge => edge.node.id === theId), 1);
        //       store.writeQuery({query, variables, data});
        //     }
        //   }
        // }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.objective {
  min-height: 50px;

  &__user-widget {
    margin-right: 0;
  }
}
</style>
