<template>
  <checkbox
    :checked="module.solutionsEnabled"
    label="Lösungen für Lernende anzeigen"
    v-if="canToggleSolutions"
    @input="toggleSolutions"
  />
</template>

<script>
import Checkbox from '@/components/ui/Checkbox.vue';
import UPDATE_SOLUTION_VISIBILITY_MUTATION from '@/graphql/gql/mutations/updateSolutionVisibility.gql';
import MODULE_FRAGMENT from '@/graphql/gql/fragments/moduleParts.gql';

import { meQuery, moduleQuery } from '@/graphql/queries';

export default {
  components: {
    Checkbox,
  },

  apollo: {
    me: meQuery,
    module: moduleQuery,
  },

  data() {
    return {
      me: {
        permissions: [],
      },
      module: {},
    };
  },

  computed: {
    canToggleSolutions() {
      return this.me.isTeacher;
    },
    slug() {
      return this.$route.params.slug;
    },
  },

  methods: {
    toggleSolutions(enabled) {
      const slug = this.slug;
      this.$apollo.mutate({
        mutation: UPDATE_SOLUTION_VISIBILITY_MUTATION,
        variables: {
          input: {
            slug,
            enabled,
          },
        },
        update(
          store,
          {
            data: {
              updateSolutionVisibility: { success, solutionsEnabled },
            },
          }
        ) {
          if (success) {
            // https://www.apollographql.com/docs/react/caching/cache-interaction/#obtaining-an-objects-cache-id
            const id = store.identify({
              __typename: 'ModuleNode',
              slug,
            });
            const fragment = MODULE_FRAGMENT;
            const fragmentName = 'ModuleLegacyParts';
            const module = store.readFragment({ fragment, fragmentName, id });
            const data = {
              ...module,
              solutionsEnabled,
            };
            store.writeFragment({ fragment, fragmentName, data, id });
          }
        },
      });
    },
  },
};
</script>
