<template>
  <base-panel
    :loading="loading"
    :full-view="fullView"
    :minimizable="minimizable"
    panel-type="project"
    data-test="project-panel"
    @minimize-panel="$store.commit('minimizeProject')"
    @maximize-panel="$store.commit('maximizeProject')">>

    <!-- Project and Summary-->
    <template slot="title">
      <v-card-title class="pa-0">
        <h2 class="font-weight-thin primary--text"><b>Project</b> | {{ projectId }}</h2>
      </v-card-title>
    </template>

    <!-- Project Actions  -->
    <template slot="actions">
      <v-tooltip
        v-if="permissions.includes('add_submission')"
        top>
        <v-icon
          slot="activator"
          small
          flat
          class="primary--text"
          @click="addNewSubmission">
          group_add
        </v-icon>
        <span>Add batch of samples</span>
      </v-tooltip>
    </template>

    <!-- Title and Info -->
    <template slot="content">

      <!-- Summary Section-->
      <v-container
        v-if="projectSummary"
        class="panel-section"
        text-xs-left>
        <p
          class="panel-details-items text-xs-left"
          v-html="projectSummary"/>
      </v-container>

      <!-- Project Details Section-->
      <v-container class="panel-section" text-xs-left>

        <!-- Title -->
        <v-layout row wrap my-2 class="panel-details-items">
          <v-flex sm12>
            <base-editable-field
              :model="project"
              :rules="[rules.required]"
              :loading="loading"
              :has-permission="permissions.includes('change_project')"
              name="Title"
              field="title"
              @update-value="updateValue"/>
          </v-flex>
        </v-layout>

        <!-- Short title -->
        <v-layout row wrap my-2 class="panel-details-items">
          <v-flex sm12>
            <base-editable-field
              :model="project"
              :rules="[rules.required, rules.unicode, rules.min10]"
              :loading="loading"
              :has-permission="permissions.includes('change_project')"
              name="Short Title"
              field="short_title"
              @update-value="updateValue"/>
          </v-flex>
        </v-layout>

        <!-- Description-->
        <v-layout row wrap my-2 class="panel-details-items">
          <v-flex sm12>
            <base-editable-field
              :model="project"
              :rules="[rules.required, rules.min10]"
              :loading="loading"
              :has-permission="permissions.includes('change_project')"
              name="Description"
              field="description"
              @update-value="updateValue"/>
          </v-flex>
        </v-layout>

        <!-- Participants -->
        <v-layout row wrap my-2 class="panel-details-items">
          <v-flex sm12>
            <base-users-static-field :participants="participants"/>
          </v-flex>
        </v-layout>

        <!-- Project Details-->
        <v-layout row wrap my-2 class="panel-details-items">

          <v-flex sm6>
            <base-static-field
              name="Results"
              size="small">
              <span
                class="active-link"
                @click="openDrive(project.drive_id)">
                Drive
              </span>
            </base-static-field>
          </v-flex>

          <v-flex sm6>
            <base-static-field
              :model="project"
              name="Usage [TB]"
              field="data.data_usage"
              size="small"/>
          </v-flex>

          <v-flex sm6>
            <base-static-field
              :model="project"
              name="Missing Data"
              field="data.experiments_missing_data"
              size="small"/>
          </v-flex>

          <v-flex sm12>
            <custom-fields :model="project"/>
          </v-flex>

          <v-flex sm12>
            <base-editable-field
              :model="project"
              :loading="loading"
              :has-permission="permissions.includes('change_project')"
              name="Notes"
              hint="Any extra information you want to add to the project."
              field="notes"
              @update-value="updateValue"/>
          </v-flex>

          <v-flex sm12>
            <tag-editable-field
              :model="project"
              :loading="loading"
              :has-permission="permissions.includes('change_project')"
              @update-value="updateValue"/>
          </v-flex>

        </v-layout>

      </v-container>

      <!-- JIRA -->
      <JiraIntegration :project="projectId" class="panel-section"/>

      <!-- Tables  -->
      <DataTable
        :params="params"
        model="analyses"/>

      <DataTable
        :params="params"
        model="experiments"/>

      <DataTable
        :params="params"
        model="samples"/>

      <DataTable
        :params="params"
        model="submissions"/>

    </template>

  </base-panel>
</template>

<script>
import { mapGetters } from 'vuex'
import BaseEditableField from '@/components/base/BaseEditableField'
import BasePanel from '@/components/base/BasePanel.vue'
import BaseStaticField from '@/components/base/BaseStaticField'
import BaseUsersStaticField from '@/components/base/BaseUsersStaticField'
import CustomFields from '@/components/base/CustomFields'
import DataTable from '@/components/search/DataTable.vue'
import JiraIntegration from '@/components/projects/JiraIntegration.vue'
import TagEditableField from '@/components/base/TagEditableField'

import { fetchRecord, updateRecord } from '@/utils/api'
import { ADD_NEW_SUBMISSION, UPDATE_PROJECT } from '@/store/actions/modals'
import rules from '@/utils/rules'

export default {
  name: 'ProjectPanel',
  components: {
    BaseEditableField,
    BasePanel,
    BaseStaticField,
    BaseUsersStaticField,
    CustomFields,
    DataTable,
    TagEditableField,
    JiraIntegration
  },
  data () {
    return {
      loading: false,
      project: {},
      rules
    }
  },
  computed: {
    ...mapGetters({
      fullView: 'isProjectPanelMaximized'
    }),
    ...mapGetters([
      'projectId',
      'submissionId',
      'permissions'
    ]),
    params () {
      return {
        'projects__pk': this.projectId
      }
    },
    projectSummary () {
      let { project } = this
      let result = []
      const keys = [
        'species',
        'source_types',
        'analytes',
        'sequencing_methods'
      ]
      keys.forEach(key => {
        if ('data' in project && key in project.data) {
          Object.keys(project.data[key]).forEach(field => {
            result.push(`${field} ` + project.data[key][field])
          })
        }
      })
      return result.join(' - ')
    },
    executiveSummary () {
      return this.$get(this.project, 'data.executive_summary', '')
    },
    minimizable () {
      return !!this.$store.getters.submissionId
    },
    participants () {
      return {
        'pi': this.$get(this.project, 'principal_investigator', ''),
        'owner': this.$get(this.project, 'owner', ''),
        'analyst': this.$get(this.project, 'analyst', ''),
        'coordinator': this.$get(this.project, 'coordinator', '')
      }
    }
  },
  watch: {
    submissionId (value) {
      !value && this.projectId && this.$store.commit('maximizeProject')
    },
    projectId () {
      this.fetchProject()
    },
    project (value) {
      this.$store.dispatch(UPDATE_PROJECT, {
        value
      })
    }
  },
  created () {
    this.fetchProject()
  },
  methods: {
    async fetchProject () {
      if (this.projectId) {
        this.loading = true
        const response = await fetchRecord('projects', this.projectId)
        this.project = response
        this.loading = false
      }
    },
    async updateValue (data) {
      if (Object.keys(data).length) {
        this.loading = true
        const response = await updateRecord('projects', this.projectId, data)
        this.project = response
        this.loading = false
      }
    },
    openDrive (driveId) {
      window.open(`https://drive.google.com/drive/folders/${driveId}`)
    },
    addNewSubmission () {
      const { project } = this
      this.$store.dispatch(ADD_NEW_SUBMISSION, {
        project
      })
    }
  }
}
</script>
