<template>
  <!-- eslint-disable vue/no-v-html -->
  <div
    data-cy="snapshot-entry"
    class="snapshot-list-item"
  >
    <router-link
      :to="snapshotRoute"
      class="snapshot-list-item__title"
      data-cy="snapshot-link"
    >
      {{ snapshot.title }}
    </router-link>
    <span
      class="snapshot-list-item__date"
      v-html="meta"
    />
    <div class="snapshot-list-item__actions">
      <button
        class="icon-button"
        data-cy="delete-snapshot-button"
        v-if="snapshot.mine"
        @click="deleteSnapshot"
      >
        <trash-icon class="snapshot-list-item__icon" />
      </button>
      <button
        class="icon-button"
        data-cy="rename-snapshot-button"
        v-if="snapshot.mine"
        @click="changeTitle"
      >
        <pen-icon class="snapshot-list-item__icon" />
      </button>
      <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>
  </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 UPDATE_SNAPSHOT_MUTATION from 'gql/mutations/snapshots/update.gql';
import DELETE_SNAPSHOT_MUTATION from 'gql/mutations/snapshots/delete.gql';
import SNAPSHOTS_QUERY from 'gql/queries/moduleSnapshots.gql';
import PenIcon from '@/components/icons/PenIcon.vue';
import TrashIcon from '@/components/icons/TrashIcon.vue';
import { removeAtIndex } from '@/graphql/immutable-operations';
import { matomoTrackEvent } from '@/helpers/matomo-client';
import { graphql } from '@/__generated__';

export const SnapshotListItemFragment = graphql(`
  fragment SnapshotListItem on SnapshotNode {
    shared
  }
`);

export const SnapshotTitleListItem = graphql(`
  fragment SnapshotTitle on SnapshotNode {
    title
  }
`);

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

  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: {
    changeTitle() {
      this.$modal
        .open('edit-snapshot-title-wizard', { name: this.snapshot.title })
        .then((title) => {
          console.log(title);
          this.$apollo.mutate({
            mutation: UPDATE_SNAPSHOT_MUTATION,
            variables: {
              input: {
                id: this.snapshot.id,
                title: title,
              },
            },
            update(
              store,
              {
                data: {
                  updateSnapshot: { snapshot },
                },
              }
            ) {
              if (snapshot.__typename === 'SnapshotNode') {
                const { id, title } = snapshot;
                store.writeFragment({
                  id,
                  fragment: SnapshotTitleListItem,
                  data: {
                    title,
                    __typename: 'SnapshotNode',
                  },
                });
              }
            },
          });
        })
        .catch();
    },
    deleteSnapshot() {
      this.$modal
        .open('confirm', {
          title: 'Snapshot löschen',
        })
        .then(() => {
          this.$apollo
            .mutate({
              mutation: DELETE_SNAPSHOT_MUTATION,
              variables: {
                input: {
                  id: this.snapshot.id,
                },
              },
              update: (
                store,
                {
                  data: {
                    deleteSnapshot: { result },
                  },
                }
              ) => {
                if (result.__typename === 'Success') {
                  const slug = this.$route.params.slug;
                  const query = SNAPSHOTS_QUERY;
                  const variables = {
                    slug,
                  };
                  const { module } = store.readQuery({
                    query,
                    variables,
                  });
                  const index = module.snapshots.findIndex((snapshot) => snapshot.id === this.snapshot.id);
                  const snapshots = removeAtIndex(module.snapshots, index);

                  const data = {
                    module: {
                      ...module,
                      snapshots,
                    },
                  };

                  store.writeQuery({
                    query,
                    variables,
                    data,
                  });
                }
              },
            })
            .then(() => {
              matomoTrackEvent('Modul Snapshot', 'Snapshot gelöscht', this.$route.params.slug);
            });
        })
        .catch(() => {});
    },
    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: SnapshotListItemFragment,
            data: {
              shared,
              __typename: 'SnapshotNode',
            },
          });
        },
      });

      const slug = this.$route.params.slug;
      if (this.snapshot.shared) {
        matomoTrackEvent('Modul Snapshot', 'Snapshot mit Team geteilt', slug);
      } else {
        matomoTrackEvent('Modul Snapshot', 'Snapshot nicht mehr geteilt', slug);
      }
    },
  },
};
</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;
  }

  &__icon {
    @include default-icon;
  }

  &__actions {
    display: flex;
    align-items: center;
    margin-left: auto;
  }
}
</style>
