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

    <v-card>
      <v-snackbar v-model="hasError" :timeout="6000" absolute top>
        {{ errorText }}
        <v-btn fab flat icon @click.native="hasError = false">
          <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">
            Cancel
          </v-btn>
        </v-card-actions>
      </v-form>
    </v-card>
  </v-dialog>
</template>

<script>
export default {
  name: 'FormDialog',
  data: () => ({
    dialog: false,
    valid: true,
    hasError: false,
    errorText: ''
  }),

  props: {
    buttonText: String
  },

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

    showError(text) {
      let actually = () => {
        this.hasError = true
        this.errorText = text
      }

      if (this.hasError) {
        this.hasError = false
        window.setTimeout(actually, 100)
      } else {
        actually()
      }
    }
  },

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