<template>
  <div class="avatar">
    <transition name="fade">
      <default-avatar
        :class="{'avatar__placeholder--highlighted': iconHighlighted}"
        class="avatar__placeholder"
        v-show="!isAvatarLoaded"/>
    </transition>
    <transition name="show">
      <div
        :style="{'background-image': `url(${avatarUrl})`}"
        class="avatar__image"
        v-show="isAvatarLoaded"
        ref="avatarImage"/>
    </transition>
    <img
      :src="avatarUrl"
      class="avatar__fake-image"
      ref="fakeImage">

    <div
      class="avatar__edit"
      v-if="editable"
      @click="closeSidebar">
      <router-link :to="{name: 'profile'}">
        <pen-icon/>
      </router-link>
    </div>
  </div>
</template>

<script>
  import DefaultAvatar from '@/components/icons/DefaultAvatar';
  import PenIcon from '@/components/icons/PenIcon';

  import TOGGLE_SIDEBAR from '@/graphql/gql/local/mutations/toggleSidebar.gql';

  export default {
    props: {
      avatarUrl: {
        type: String
      },
      iconHighlighted: {},
      editable: {
        default: false
      }
    },
    components: {
      DefaultAvatar,
      PenIcon
    },
    data() {
      return {
        isAvatarLoaded: false
      };
    },
    mounted() {
      if (this.avatarUrl !== '') {
        this.$refs.fakeImage.addEventListener('load', () => {
          if (this.$refs.fakeImage) {
            this.$refs.fakeImage.remove();
            this.isAvatarLoaded = true;
          }
        });
      }
    },
    methods: {
      closeSidebar() {
        this.$apollo.mutate({
          mutation: TOGGLE_SIDEBAR,
          variables: {
            profile: false
          }
        });
      }
    }
  };
</script>

<style scoped lang="scss">
  @import "~styles/helpers";

  $max-width: 100%;

  .avatar {
    height: $max-width;
    width: $max-width;
    overflow: hidden;
    text-align: center;

    &__placeholder {
      height: $max-width;
      fill: $color-silver-dark;
      border-radius: 50%;

      &--highlighted {
        fill: $color-brand;
      }
    }

    &__image {
      background-size: cover;
      background-position: center center;
      height: 100%;
      width: 100%;
      border: 0;
      border-radius: 50%;

      &--landscape {
        width: auto;
        height: $max-width;
      }
    }

    &__fake-image {
      width: 0;
      height: 0;
    }

    &__edit {
      position: absolute;
      box-sizing: border-box;
      width: 34px;
      height: 34px;
      display: block;
      left: 50%;
      bottom: -3px;
      transform: translateX(80%);
      background-color: $color-white;
      border-radius: 50%;
      padding: 6px;
      box-shadow: 0 3px 10px rgba(0, 0, 0, 0.12);
    }

    .fade-leave-active, .show-enter-active {
      transition: opacity .5s;
    }
    .fade-leave-to, .show-enter {
      opacity: 0;
    }

    .show-enter-to {
      opacity: 1;
    }
  }
</style>
