<template>
  <div class="ui-page full-width" :class="{ 'ui-page_two-col': twoCol }">
    <div class="ui-page__before" ref="scrollableWrap" :style="style">
      <slot></slot>
      <slot name="before"></slot>
    </div>
    <template v-if="twoCol">
      <q-separator vertical class="ui-page__separator" />
      <div class="full-width ui-page__after bg-background" :style="style">
        <slot name="after"></slot>
      </div>
    </template>
  </div>
</template>

<script lang="ts">
import { Component, Inject, Prop, Ref, Vue } from 'vue-property-decorator'
import { QSeparator, scroll } from 'quasar'

interface Layout {
  header: {
    space: boolean
    size: number
  }
  footer: {
    space: boolean
    size: number
  }
}

@Component({ inheritAttrs: false, components: { QSeparator } })
export default class UiPageLayout extends Vue {
  @Prop({ type: Boolean, default: () => false }) twoCol!: number
  @Prop(String) selectorToScroll!: string

  @Inject('layout') layout!: Layout
  @Ref('scrollableWrap') scrollableWrap!: HTMLElement

  mounted() {
    this.$nextTick(() => {
      if (this.selectorToScroll) {
        const elementToScroll = this.scrollableWrap.querySelector(
          this.selectorToScroll
        )

        if (elementToScroll) {
          scrollToElement(
            elementToScroll as HTMLElement,
            this.scrollableWrap as HTMLElement
          )
        }
      }
    })
  }

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

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

function scrollToElement(el: HTMLElement, target: HTMLElement) {
  const offset = el.offsetTop
  const duration = 300

  if (offset > 100) {
    scroll.setScrollPosition(target, offset, duration)
  }
}
</script>
