<template>
  <q-splitter
    v-on="$listeners"
    v-bind="$attrs"
    v-model="value"
    :limits="_limits"
    :unit="isPixelUnit && !full ? 'px' : '%'"
    separator-class="ui-splitter__separator"
    :class="{
      'ui-splitter_full': this.full,
    }"
    :before-class="beforeClass"
    :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, Inject, Prop, Vue } from 'vue-property-decorator'
import { QSplitter } from 'quasar'

const FULL_VALUE = 100

@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[]
  @Prop({ type: Number, default: 50 }) defaultValue!: number
  @Prop({ type: String, default: 'bg-background' }) beforeClass!: string

  @Inject('layout') layout: any

  splitValue = this.defaultValue

  created() {
    this.splitValue = this.restoreSplitValue() ?? this.defaultValue
  }

  get value() {
    return this.full ? FULL_VALUE : this.splitValue
  }

  set value(value) {
    if (!this.full) {
      this.splitValue = value
      this.saveSplitValue(value)
    }
  }

  get localStorageKey(): string {
    return `ui-page-splitter:${this.id}`
  }

  restoreSplitValue() {
    const restoredValue = localStorage.getItem(this.localStorageKey)

    return restoredValue !== null ? parseInt(restoredValue) : null
  }

  saveSplitValue(value: number) {
    localStorage.setItem(this.localStorageKey, value.toString())
  }

  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 _limits(): number | number[] {
    return this.full ? [0, this.isPixelUnit ? 100000 : 100] : this.limits
  }
}
</script>
