<template>
  <div class="snapshot-list-item">
    <router-link
      :to="snapshotRoute"
      class="snapshot-list-item__title"
      data-cy="snapshot-link"
      v-html="snapshot.title"/>
    <span
      class="snapshot-list-item__date"
      v-html="meta"/>
    <a
      class="snapshot-list-item__link"
      v-if="snapshot.mine"
      @click="share"
    >
      <template v-if="snapshot.shared">Nicht mehr teilen</template>
      <template v-else>Mit Team teilen</template>
    </a>
  </div>
</template>

<script>
  import dateformat from '@/helpers/date-format';
  import {SNAPSHOT_DETAIL} from '@/router/module.names';
  import SHARE_SNAPSHOT_MUTATION from 'gql/mutations/snapshots/share.gql';
  import gql from 'graphql-tag';

  export default {
    props: {
      snapshot: {
        type: Object,
        default: () => ({}),
      },
    },

    computed: {
      meta() {
        const created = dateformat(this.snapshot.created);
        if (this.snapshot.mine) {
          return created;
        }
        return `${created} - ${this.snapshot.creator}`;
      },
      snapshotRoute() {
        return {
          name: SNAPSHOT_DETAIL,
          params: {
            id: this.snapshot.id,
          },
        };
      },
    },

    methods: {
      share() {
        this.$apollo.mutate({
          mutation: SHARE_SNAPSHOT_MUTATION,
          variables: {
            input: {
              snapshot: this.snapshot.id,
              shared: !this.snapshot.shared,
            },
          },
          update(store, {data: {shareSnapshot: {snapshot: {id, shared}}}}) {
            store.writeFragment({
              id,
              fragment: gql`fragment SnapshotFragment on SnapshotNode { shared }`,
              data: {
                shared,
                __typename: 'SnapshotNode'
              }
            });
          }
        });
      },
    },
  };
</script>

<style scoped lang="scss">
  @import '~styles/helpers';

  .snapshot-list-item {
    display: flex;
    align-items: center;
    justify-content: flex-start;

    &__title {
      @include heading-4;
      width: 180px;
    }

    &__date {
      @include regular-text;
    }

    &__link {
      @include default-link;
      color: $color-brand;
      margin-left: auto;
    }
  }
</style>
