<template>
  <v-dialog v-model="dialog">
    <v-btn flat slot="activator">
      {{ buttonText }}
    </v-btn>

    <v-card>
      <v-snackbar
        v-model="snackbar.visible"
        :timeout="6000"
        :color="snackbar.color"
        absolute
        top
      >
        {{ snackbar.text }}
        <v-btn @click.native="snackbar.visible = false" fab flat icon>
          <v-icon>close</v-icon>
        </v-btn>
      </v-snackbar>

      <v-form
        ref="form"
        v-model="valid"
        @submit.prevent="validate"
        lazy-validation
      >
        <slot></slot>

        <v-divider></v-divider>

        <v-card-actions>
          <v-spacer></v-spacer>

          <v-btn color="success" type="submit" :disabled="!valid">
            {{ buttonText }}
          </v-btn>

          <v-btn color="error" @click.native="dialog = false">
            Close
          </v-btn>
        </v-card-actions>
      </v-form>
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  name: 'FormDialog',
  data: () => ({
    dialog: false,
    valid: true,
    snackbar: {
      visible: false,
      color: '',
      text: ''
    }
  }),

  props: {
    buttonText: String
  },

  methods: {
    validate() {
      if (this.$refs.form.validate()) {
        this.$emit('validated')
      }
    },

    showSnackbar(text, color) {
      if (text == '') return

      this.snackbar.visible = false

      window.setTimeout(() => {
        this.snackbar.text = text
        this.snackbar.color = color
        this.snackbar.visible = true
      }, 100)
    }
  },

  watch: {
    dialog(val) {
      if (val) {
        requestAnimationFrame(() => {
          this.$parent.$refs.autofocus.focus()
        })
      } else {
        this.$refs.form.resetValidation()
      }
    }
  }
}
</script>
