<template>
  <div class="profile">
    <h1 class="profile__header">Profilbild</h1>
    <div
      class="profile-avatar"
      v-if="me.avatarUrl" >
      <div class="profile-avatar__image">
        <avatar :avatar-url="me.avatarUrl" />
      </div>
      <a
        class="profile-avatar__remove icon-button"
        @click="deleteAvatar()">
        <trash-icon class="profile-avatar__remove-icon icon-button__icon"/>
      </a>
    </div>
    <avatar-upload-form
      v-else
      @avatarUpdate="updateAvatar"/>
  </div>
</template>

<script>
  import UPDATE_AVATAR_QUERY from '@/graphql/gql/mutations/updateAvatarUrl.gql';
  import ME_QUERY from '@/graphql/gql/queries/meQuery.gql';
  import AvatarUploadForm from '@/components/profile/AvatarUploadForm';
  import Avatar from '@/components/profile/Avatar';
  import TrashIcon from '@/components/icons/TrashIcon';

  export default {
    components: {
      AvatarUploadForm,
      Avatar,
      TrashIcon
    },

    data() {
      return {
        me: {
          avatarUrl: ''
        }
      };
    },
    apollo: {
      me: {
        query: ME_QUERY,
      },
    },
    methods: {
      deleteAvatar () {
        this.updateAvatar('');
      },
      updateAvatar (url) {
        this.$apollo.mutate({
          mutation: UPDATE_AVATAR_QUERY,
          variables: {
            input: {
              avatarUrl: url
            }
          },
          update(store, {data: {updateAvatar: {success}}}) {
            if (success) {
              const data = store.readQuery({query: ME_QUERY});
              if (data) {
                data.me.avatarUrl = url;
                store.writeQuery({query: ME_QUERY, data});
              }
            }
          }
        }).catch((error) => {
          console.warn('UploadError', error);
        });
      }
    }
  };
</script>

<style scoped lang="scss">
  @import "@/styles/_variables.scss";

  .profile-avatar {
    display: flex;
    flex-direction: row;

    &__image {
      height: 230px;
      width: 230px;
    }
  }

  .profile-avatar {
    margin-bottom: $large-spacing;
  }

</style>
