<template>
  <base-modal
    :show-modal="showModal"
    max-width="800px"
    @close-modal="closeModal">

    <template slot="title">
      Create New Project?
    </template>

    <template slot="content">
      <v-container grid-list-md>
        <v-layout wrap>

          <v-flex xs12>
            <v-text-field
              ref="title"
              v-model="project.title"
              :rules="[rules.required]"
              label="Project Title"/>
          </v-flex>

          <v-flex xs12 sm6>
            <v-text-field
              ref="shortTitle"
              v-model="project.shortTitle"
              :rules="[rules.required, rules.unicode, rules.min10]"
              label="Project Short Title"
              counter
              maxlength="30"
              hint="Think of the objective of the project."/>
          </v-flex>

          <v-flex xs12 sm6>
            <v-select
              ref="group"
              v-model="project.group"
              :items="['CHM', 'PEDS', 'Other']"
              :rules="[rules.required]"
              label="Group"/>
          </v-flex>

          <v-flex xs12 sm6>
            <user-search-input
              ref="principalInvestigator"
              v-model="project.principalInvestigator"
              :rules="[rules.required, rules.email]"
              label="Principal Investigator"
              hint="Laboratory head or principal investigator"/>
          </v-flex>

          <v-flex xs12 sm6>
            <user-search-input
              ref="owner"
              v-model="project.owner"
              :rules="[rules.required, rules.email]"
              label="Project Owner"
              hint="Who deals with the nitty-gritty of the project"/>
          </v-flex>

          <v-flex xs12 sm6>
            <user-search-input
              ref="coordinator"
              v-model="project.coordinator"
              :rules="[rules.required, rules.email]"
              label="Coordinator"
              hint="Project manager or coordinator"/>
          </v-flex>

          <v-flex xs12 sm6>
            <user-search-input
              ref="analyst"
              v-model="project.analyst"
              :rules="[rules.required, rules.email]"
              label="Data Analyst"
              hint="Person responsible for the data analysis"/>
          </v-flex>

        </v-layout>
      </v-container>
    </template>

    <template slot="footer-actions">
      <v-btn
        color="primary darken-1"
        flat="flat"
        @click="submit">
        Create
      </v-btn>
    </template>

  </base-modal>
</template>

<script>
import BaseModal from '@/components/base/BaseModal.vue'
import UserSearchInput from '@/components/projects/UserSearchInput'
import rules from '@/utils/rules'
import { createRecord } from '@/utils/api'
import { SHOW_ALERT } from '@/store/actions/alert'
import { SHOW_PANEL } from '@/store/actions/panels'

export default {
  name: 'NewProjectModal',
  components: {
    BaseModal,
    UserSearchInput
  },
  props: {
    showModal: {
      type: Boolean,
      default: false,
      required: true
    },
    projects: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      project: {},
      users: [],
      usersQuery: '',
      isLoading: false,
      rules,
      formHasErrors: false,
      fieldsToValidate: [
        'title',
        'shortTitle',
        'group',
        'principalInvestigator',
        'owner',
        'coordinator',
        'analyst'
      ],
      refs: {}
    }
  },
  mounted () {
    // Map all local and nested inputs to local 'refs'
    this.fieldsToValidate.forEach(field => {
      if (typeof this.$refs[field].reset === 'function') {
        this.refs[field] = this.$refs[field]
      } else {
        this.refs[field] = this.$refs[field].$refs.userSearchInput
      }
    })
  },
  methods: {
    resetForm () {
      this.formHasErrors = false
      this.fieldsToValidate.forEach(field => {
        this.refs[field].reset()
      })
    },
    closeModal () {
      this.resetForm()
      this.$emit('close-modal')
    },
    async submit () {
      this.formHasErrors = false

      this.fieldsToValidate.forEach(field => {
        if (!this.project[field]) {
          this.formHasErrors = true
        }
        this.refs[field].validate(true)
      })

      if (!this.formHasErrors) {
        const response = await createRecord('projects', this.project)
        const projectId = this.$get(response, 'pk', '')

        if (projectId) {
          this.$store.dispatch(SHOW_ALERT, {
            message: `Project ${projectId} was succesfully created.`
          })
          this.$store.dispatch(SHOW_PANEL, {
            project: projectId
          })
          this.closeModal()
        } else {
          const message = this.$get(
            response,
            'error',
            'The project could not be created. Please try again.'
          )
          this.$store.dispatch(SHOW_ALERT, {
            error: message
          })
        }
      }
    }
  }
}
</script>
