<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';
  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.permissions.includes('users.can_manage_school_class_content');
      },
      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) {
              const id = `ModuleNode:${slug}`;
              const fragment = MODULE_FRAGMENT;
              const data = store.readFragment({fragment, id});
              data.solutionsEnabled = solutionsEnabled;
              store.writeFragment({fragment, data, id});
            }
          }
        });
      }
    },
  };
</script>
