<template>
  <div v-if="loadingBar" class="loadingbar-wrapper">
    <div :class="{ 'loadingbar-background-wrapper': !transparent }">
      <div class="loadingbar-background" :class="color" :style="{ height: height + 'px' }"></div>
    </div>
    <div class="loadingbar" :class="color" :style="{ height: height + 'px', width: 'calc(100% / 100 * ' + loadingValue + ')'}"></div>
  </div>
</template>

<script>

export default {
  name: 'LoadingBar',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    height: {
      type: Number,
      default: 2
    },
    color: {
      type: String,
      default: 'primary'
    },
    transparent: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      loadingValue: 0,
      loadingBar: false,
      loadingTimeout: null
    }
  },
  watch: {
    loading: {
      immediate: true,
      handler (value) {
        clearTimeout(this.loadingTimeout)
        if (value) {
          this.loadingValue = 0
          this.loadingBar = true
          this.loadingTimeout = setTimeout(this.increaseLoadingValue, 10)
        } else {
          this.loadingValue = 100
          this.loadingTimeout = setTimeout(() => { this.loadingBar = false }, 500)
        }
      }
    }
  },
  methods: {
    increaseLoadingValue () {
      if (this.loading && this.loadingValue <= 85) {
        this.loadingValue += 10
        this.loadingTimeout = setTimeout(this.increaseLoadingValue, 200)
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.loadingbar-wrapper {
  width: 100%;
  height: 0;
  z-index: 1;
  position: relative;
}

.loadingbar-background {
  width: 100%;
  height: 100%;
  opacity: 0.3;
}

.loadingbar {
  top: 0;
  left: 0;
  position: absolute;
  transition: width .2s linear ;
}

.theme--dark .loadingbar-background-wrapper {
  background-color: #424242;
}

.theme--light .loadingbar-background-wrapper {
  background-color: #fff;
}
</style>
