<template>
  <div class="color-picker">
    <h3 class="subtitle is-3">Couleur</h3>
    <div class="columns is-mobile is-centered is-multiline">
      <div class="column" v-for="(color, k) in colors" :key="k">
        <div
          @click.prevent="select(color)"
          class="color-container"
          :class="{ white: color.label }"
          :style="colorBackground(color)"
        >
          <awe-icon v-if="color.value === localColor" icon="check" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue, Model, Watch } from 'vue-property-decorator'
import IColor from '@/models/IColor'
import colors from '@/data/colors'

@Component
export default class ColorPicker extends Vue {
  @Model('input', { type: String, required: false })
  public color!: string | null
  public localColor: string | null = null
  public colorLabel: string | null = null
  public colors: IColor[] = colors

  public mounted(): void {
    this.localColor = this.color
    if (this.color) {
      const color: IColor | undefined = this.colors.find(
        (c: IColor) => c.value === this.color
      )
      if (color) {
        this.colorLabel = color.label
      }
    } else {
      this.localColor = this.colors[0].value
    }
  }

  public select(color: IColor): void {
    this.localColor = color.value
    this.colorLabel = color.label
  }

  public colorBackground(color: IColor): any {
    return {
      border: !color.label ? '1px solid #95afc0' : '',
      backgroundColor: color.value
    }
  }

  public get background(): any | null {
    if (!this.localColor) {
      return null
    }
    return {
      'background-color': this.localColor
    }
  }

  @Watch('localColor')
  public onColorChange(color: string | null, oldColor: string | null) {
    this.$emit('input', color)
    if (oldColor !== color) {
      this.$emit('color-change')
    }
  }
}
</script>

<style lang="scss" scoped>
.color-container {
  border-radius: 6px;
  width: 50px;
  height: 50px;
  line-height: 50px;
  font-size: 25px;
  margin: auto;
  &.white {
    color: white;
  }
  &:hover {
    cursor: pointer;
  }
}
.input {
  width: 100px;
}
.button.is-static {
  width: 50px;
}
</style>
