import ME_QUERY from '@/graphql/gql/queries/meQuery.gql';
import UPDATE_USER_SETTING from '@/graphql/gql/mutations/updateUserSetting.gql';
import MY_SCHOOL_CLASS_QUERY from '@/graphql/gql/queries/mySchoolClass.gql';
// import DELETE_MODULE_NODES from '@/graphql/gql/local/mutations/deleteModuleNodes.gql';
import MODULE_DETAILS_QUERY from '@/graphql/gql/queries/modules/moduleDetailsQuery.gql';

export default {
  methods: {
    updateSelectedClass(selectedClass) {
      // const innerApollo = this.$apollo;
      return this.$apollo
        .mutate({
          mutation: UPDATE_USER_SETTING,
          variables: {
            input: {
              id: selectedClass.id,
            },
          },
          update(store) {
            let { me } = store.readQuery({ query: ME_QUERY });

            console.log(`storing in cache: ${selectedClass.name}`);
            const data = {
              me: {
                ...me,
                selectedClass: {
                  readOnly: false, // assume this, it will be reloaded later anyway
                  ...selectedClass,
                },
              },
            };
            console.log(`writing data`, data);

            store.writeQuery({ query: ME_QUERY, data });

            // todo: still needed for anything? asking chrigu @05.09.22, but commenting it for bugfix
            //   innerApollo.mutate({
            //     mutation: DELETE_MODULE_NODES
            // });
          },
          refetchQueries: [
            {
              query: MY_SCHOOL_CLASS_QUERY,
            },
            {
              query: MODULE_DETAILS_QUERY,
              variables: {
                slug: this.$route.params.slug,
              },
            },
          ],
        })
        .catch((error) => {
          console.warn('failed to update selected class', error);
        });
    },
  },
};
