<template>
  <q-splitter
    v-on="$listeners"
    v-bind="$attrs"
    v-model="value"
    :limits="_limits"
    :unit="isPixelUnit && !full ? 'px' : '%'"
    before-class="bg-background"
    separator-class="ui-splitter__separator"
    :class="{
      'ui-splitter_full': this.full,
    }"
    :style="style"
  >
    <template slot="before">
      <slot name="before" />
    </template>
    <template slot="after">
      <slot name="after" />
    </template>
    <template slot="separator">
      <span></span>
    </template>
  </q-splitter>
</template>

<script lang="ts">
import {
  Component,
  Emit,
  Inject,
  Prop,
  Vue,
  Watch,
} from 'vue-property-decorator'
import { QSplitter } from 'quasar'

@Component({ inheritAttrs: false, components: { QSplitter } })
export default class UiPageSplitter extends Vue {
  @Prop({ type: String, required: true }) id!: string
  @Prop(Boolean) full?: boolean
  @Prop(Boolean) isPixelUnit?: boolean
  @Prop({ type: Array, default: () => [0, 100] }) limits!: number[]

  @Inject('layout') layout: any

  value = 50
  previousValue: number | null = null

  created() {
    if (this.full) {
      return
    }

    const savedValue = localStorage.getItem(this.localStorageKey)

    if (savedValue) {
      this.value = parseInt(savedValue)
    }
  }

  get style(): string {
    const offset =
      (this.layout.header.space === true ? this.layout.header.size : 0) +
      (this.layout.footer.space === true ? this.layout.footer.size : 0)

    return `height: ${this.$q.screen.height - offset + 'px'}`
  }

  get localStorageKey(): string {
    return this.id
  }

  get _limits(): number | number[] {
    return this.full ? [0, this.isPixelUnit ? 100000 : 100] : this.limits
  }

  @Emit()
  input(value: number) {
    if (!this.full) {
      localStorage.setItem(this.localStorageKey, value.toString())
    }

    this.value = value
  }

  @Watch('full', { immediate: true })
  updateValue(full: boolean) {
    if (full) {
      this.previousValue = this.value
      this.value = 100
    } else {
      this.value = this.previousValue ? this.previousValue : 50
    }
  }
}
</script>
