<template>
  <div
    class="project-actions"
    data-cy="project-actions">
    <a
      class="project-actions__more-link"
      @click.stop="toggleMenu">
      <ellipses/>
    </a>
    <widget-popover
      class="project-actions__popover"
      v-if="showMenu"
      @hide-me="showMenu = false">
      <li class="popover-links__link">
        <a
          data-cy="delete-project"
          @click="deleteProject(id)">Projekt löschen</a>
      </li>
      <li class="popover-links__link">
        <a
          data-cy="edit-project"
          @click="editProject(id)">Projekt bearbeiten</a>
      </li>
      <li
        class="popover-links__link"
        v-if="!final && shareButtons"><a
          data-cy="share-project"
          @click="updateProjectShareState(id, true)">Projekt teilen</a></li>
      <li
        class="popover-links__link"
        v-if="final && shareButtons"><a
          data-cy="unshare-project"
          @click="updateProjectShareState(id, false)">Projekt nicht mehr teilen</a>
      </li>
    </widget-popover>
  </div>

</template>

<script>
import Ellipses from '@/components/icons/Ellipses.vue';
import WidgetPopover from '@/components/ui/WidgetPopover';

import DELETE_PROJECT_MUTATION from '@/graphql/gql/mutations/deleteProject.gql';
import PROJECTS_QUERY from '@/graphql/gql/queries/allProjects.gql';

import updateProjectShareState from '@/mixins/update-project-share-state';

export default {
  props: {
    id: {
      type: String,
      default: '',
    },
    final: {
      type: Boolean,
      default: false,
    },
    shareButtons: {
      type: Boolean,
      default: true,
    },
  },

  mixins: [updateProjectShareState],

  components: {
    Ellipses,
    WidgetPopover,
  },

  data() {
    return {
      showMenu: false,
    };
  },

  methods: {
    toggleMenu: function () {
      this.showMenu = !this.showMenu;
    },
    editProject(id) {
      this.$router.push({name: 'edit-project', params: {id}});
    },
    deleteProject(id) {
      this.$apollo.mutate({
        mutation: DELETE_PROJECT_MUTATION,
        variables: {
          input: {
            id,
          },
        },
        update(store, {data: {deleteProject: {success}}}) {
          if (success) {
            const data = store.readQuery({query: PROJECTS_QUERY});

            if (data) {
              data.projects.edges.splice(data.projects.edges.findIndex(edge => edge.node.id === id), 1);
              store.writeQuery({query: PROJECTS_QUERY, data});
            }
          }
        },
      }).then(() => {
        this.$router.push('/portfolio');
      });
    },
  },
};
</script>

<style scoped lang="scss">
@import "~styles/_helpers.scss";

.project-actions {
  position: relative;

  &__more-link {
    cursor: pointer;
  }

  &__popover {
    @include popover-defaults();
    min-width: 200px;
  }

  svg {
    width: 30px;
    fill: $color-charcoal-dark;
    margin-right: 15px;
  }
}
</style>
