<template>
  <div class="columns fixed-page shot">
    <div class="column main-column">
      <div class="page-header flexrow">
        <router-link
          class="flexrow-item has-text-centered back-link"
          :to="getShotsRoute"
        >
          <icon name="chevron-left" />
        </router-link>
        <span class="flexrow-item ml2">
          <entity-thumbnail
            v-if="currentShot"
            class="entity-thumbnail"
            :entity="currentShot"
            :empty-width="120"
            :empty-height="50"
            :width="120"
            :height="50"
            :with-link="false"
          />
        </span>
        <div class="flexrow-item">
          <page-title
            :text="title"
            class="entity-title"
          />
        </div>
      </div>

      <div class="flexrow infos">
        <div class="flexrow-item block flexcolumn">
          <page-subtitle :text="$t('shots.tasks')" />
          <entity-task-list
            class="task-list"
            :entries="currentTasks.map((t) => t.id)"
            :is-loading="!currentShot"
            :is-error="false"
            @task-selected="onTaskSelected"
          />
        </div>
        <div class="flexrow-item block flexcolumn">
          <div class="flexrow">
            <page-subtitle :text="$t('main.info')" />
            <div class="filler" />
            <div class="flexrow-item has-text-right">
              <button-simple
                v-if="isCurrentUserManager"
                icon="edit"
                @click="modals.edit = true"
              />
            </div>
          </div>
          <div class="table-body">
            <table
              v-if="currentShot"
              class="datatable no-header"
            >
              <tbody class="datatable-body">
                <tr class="datatable-row">
                  <td class="field-label">
                    {{ $t('shots.fields.description') }}
                  </td>
                  <description-cell
                    :entry="currentShot"
                    :full="true"
                  />
                </tr>

                <tr class="datatable-row">
                  <td class="field-label">
                    {{ $t('shots.fields.nb_frames') }}
                  </td>
                  <td>
                    {{ currentShot ? currentShot.nb_frames : '' }}
                  </td>
                </tr>

                <tr
                  v-if="
                    currentShot && currentShot.data && currentShot.data.frame_in
                  "
                  class="datatable-row"
                >
                  <td class="field-label">
                    {{ $t('shots.fields.frame_in') }}
                  </td>
                  <td>
                    {{ currentShot ? currentShot.data.frame_in : '' }}
                  </td>
                </tr>

                <tr
                  v-if="
                    currentShot &&
                      currentShot.data &&
                      currentShot.data.frame_out
                  "
                  class="datatable-row"
                >
                  <td class="field-label">
                    {{ $t('shots.fields.frame_out') }}
                  </td>
                  <td>
                    {{ currentShot ? currentShot.data.frame_out : '' }}
                  </td>
                </tr>

                <tr
                  v-if="currentShot && currentShot.data && currentShot.data.fps"
                  class="datatable-row"
                >
                  <td class="field-label">
                    {{ $t('shots.fields.fps') }}
                  </td>
                  <td>
                    {{ currentShot ? currentShot.data.fps : '' }}
                  </td>
                </tr>

                <tr
                  v-if="
                    currentShot &&
                      currentShot.data &&
                      currentShot.data.resolution
                  "
                  class="datatable-row"
                >
                  <td class="field-label">
                    {{ $t('shots.fields.resolution') }}
                  </td>
                  <td>
                    {{ currentShot ? currentShot.data.resolution : '' }}
                  </td>
                </tr>

                <tr
                  v-if="
                    currentShot &&
                      currentShot.data &&
                      currentShot.data.max_retakes
                  "
                  class="datatable-row"
                >
                  <td class="field-label">
                    {{ $t('shots.fields.max_retakes') }}
                  </td>
                  <td>
                    {{ currentShot ? currentShot.data.max_retakes : '' }}
                  </td>
                </tr>

                <tr
                  v-for="descriptor in shotMetadataDescriptors"
                  :key="descriptor.id"
                  class="datatable-row"
                >
                  <td class="field-label">
                    {{ descriptor.name }}
                  </td>
                  <td>
                    {{
                      currentShot && currentShot.data
                        ? currentShot.data[descriptor.field_name]
                        : ''
                    }}
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>

      <div class="shot-data block">
        <div class="flexrow">
          <combobox-styled
            v-model="currentSection"
            class="section-combo flexrow-item"
            :options="entityNavOptions"
          />
          <span v-show="currentSection === 'casting'">
            {{ nbAssets }} {{ $tc('assets.number', nbAssets) }}
          </span>
          <span
            v-show="
              currentSection === 'casting' && currentShot.is_casting_standby
            "
            class="tag tag-standby"
          >
            {{ $t('breakdown.fields.standby') }}
          </span>
          <div class="filler" />
          <span
            v-show="currentSection === 'schedule'"
            class="flexrow-item mt05"
          >
            {{ $t('schedule.zoom_level') }}:
          </span>
          <combobox-number
            v-show="currentSection === 'schedule'"
            v-model="zoomLevel"
            class="zoom-level flexrow-item"
            :options="zoomOptions"
            is-simple
          />
        </div>

        <div
          v-show="currentSection === 'casting'"
          class="shot-casting"
        >
          <div v-if="currentShot">
            <div
              v-if="
                currentShot &&
                  currentShot.castingAssetsByType &&
                  currentShot.castingAssetsByType[0].length > 0
              "
            >
              <div
                v-for="typeAssets in currentShot.castingAssetsByType"
                :key="
                  typeAssets.length > 0 ? typeAssets[0].asset_type_name : ''
                "
                class="type-assets"
              >
                <div class="asset-type">
                  {{
                    typeAssets.length > 0 ? typeAssets[0].asset_type_name : ''
                  }}
                  ({{ typeAssets.length }})
                </div>
                <div class="asset-list">
                  <router-link
                    v-for="asset in typeAssets"
                    :key="asset.id"
                    class="asset-link"
                    :to="buildAssetRoute(asset)"
                  >
                    <entity-thumbnail
                      class="entity-thumbnail"
                      :entity="asset"
                      :square="true"
                      :empty-width="103"
                      :empty-height="103"
                      :with-link="false"
                      :no-cache="true"
                    />
                    <div>
                      {{ asset.asset_name }}
                      <span v-if="asset.nb_occurences > 1">
                        ({{ asset.nb_occurences }})
                      </span>
                    </div>
                    <div class="ready-for flexrow">
                      <task-type-name
                        v-if="asset.ready_for"
                        class="flexrow-item"
                        :task-type="taskTypeMap.get(asset.ready_for)"
                        :current-production-id="currentProduction.id"
                        :title="
                          'Ready for: ' + taskTypeMap.get(asset.ready_for).name
                        "
                      />
                    </div>
                  </router-link>
                </div>
              </div>
            </div>
            <div
              v-else
              class="mt1"
            >
              {{ $t('shots.no_casting') }}
            </div>
          </div>
          <table-info
            v-else
            :is-loading="casting.isLoading"
            :is-error="casting.isError"
          />
        </div>

        <div
          v-if="scheduleItems[0].children.length > 0"
          v-show="currentSection === 'schedule'"
          class="schedule mt1"
        >
          <div class="wrapper">
            <schedule
              ref="schedule-widget"
              :start-date="tasksStartDate"
              :end-date="tasksEndDate"
              :hierarchy="scheduleItems"
              :zoom-level="zoomLevel"
              :is-loading="false"
              :is-estimation-linked="true"
              :hide-root="true"
              :with-milestones="false"
            />
          </div>
        </div>

        <entity-preview-files
          v-if="currentSection === 'preview-files'"
          :entity="currentShot"
        />

        <entity-news
          v-if="currentSection === 'activity'"
          :entity="currentShot"
        />

        <entity-time-logs
          v-if="currentSection === 'time-logs'"
          :entity="currentShot"
        />
      </div>
    </div>

    <div
      v-if="currentTask"
      class="column side-column"
    >
      <task-info :task="currentTask" />
    </div>

    <edit-shot-modal
      ref="edit-shot-modal"
      :active="modals.edit"
      :is-loading="loading.edit"
      :is-error="errors.edit"
      :shot-to-edit="currentShot"
      @cancel="modals.edit = false"
      @confirm="confirmEditShot"
    />
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

import { episodifyRoute } from '@/lib/path'
import { entityMixin } from '@/components/mixins/entity'
import { formatListMixin } from '@/components/mixins/format'

import ButtonSimple from '@/components/widgets/ButtonSimple'
import ComboboxNumber from '@/components/widgets/ComboboxNumber'
import ComboboxStyled from '@/components/widgets/ComboboxStyled'
import DescriptionCell from '@/components/cells/DescriptionCell'
import EditShotModal from '@/components/modals/EditShotModal'
import EntityNews from '@/components/pages/entities/EntityNews'
import EntityPreviewFiles from '@/components/pages/entities/EntityPreviewFiles'
import EntityTaskList from '@/components/lists/EntityTaskList'
import EntityTimeLogs from '@/components/pages/entities/EntityTimeLogs'
import EntityThumbnail from '@/components/widgets/EntityThumbnail'
import Icon from '@/components/widgets/Icon'
import PageTitle from '@/components/widgets/PageTitle'
import PageSubtitle from '@/components/widgets/PageSubtitle'
import Schedule from '@/components/pages/schedule/Schedule'
import TableInfo from '@/components/widgets/TableInfo'
import TaskInfo from '@/components/sides/TaskInfo'
import TaskTypeName from '@/components/widgets/TaskTypeName'

export default {
  name: 'Shot',
  mixins: [entityMixin, formatListMixin],
  components: {
    ButtonSimple,
    ComboboxNumber,
    ComboboxStyled,
    DescriptionCell,
    EditShotModal,
    EntityNews,
    EntityPreviewFiles,
    EntityTaskList,
    EntityTimeLogs,
    EntityThumbnail,
    Icon,
    PageSubtitle,
    PageTitle,
    Schedule,
    TableInfo,
    TaskInfo,
    TaskTypeName
  },

  data() {
    return {
      currentShot: null,
      currentTask: null,
      casting: {
        isLoading: false,
        isError: false
      },
      errors: {
        edit: false
      },
      loading: {
        edit: false
      },
      modals: {
        edit: false,
        preview: false
      }
    }
  },

  mounted() {
    this.clearSelectedTasks()
    this.getCurrentShot()
      .then((shot) => {
        this.currentShot = shot
        this.currentSection = this.route.query.section || 'casting'
        this.casting.isLoading = true
        this.casting.isError = false
        if (this.currentShot) {
          this.loadShotCasting(this.currentShot)
            .then(() => this.loadShotCasting(this.currentShot))
            .then(() => {
              this.casting.isLoading = false
            })
            .catch((err) => {
              this.casting.isLoading = false
              this.casting.isError = true
              console.error(err)
            })
        } else {
          this.resetData()
        }
      })
      .catch(console.error)
  },

  computed: {
    ...mapGetters([
      'currentEpisode',
      'currentProduction',
      'getTaskTypePriority',
      'isCurrentUserManager',
      'isTVShow',
      'route',
      'shotMap',
      'shotMetadataDescriptors',
      'shotSearchText',
      'shotsPath',
      'taskMap',
      'taskTypeMap'
    ]),

    title() {
      if (this.currentShot) {
        if (this.currentShot.episode_name) {
          return (
            `${this.currentShot.episode_name} / ` +
            `${this.currentShot.sequence_name} / ` +
            `${this.currentShot.name}`
          )
        } else {
          return (
            `${this.currentShot.sequence_name} / ` + `${this.currentShot.name}`
          )
        }
      } else {
        return 'Loading...'
      }
    },

    shotThumbnailPath() {
      const previewId = this.currentShot.preview_file_id
      return `/api/pictures/originals/preview-files/${previewId}.png`
    },

    isPreview() {
      return (
        this.currentShot &&
        this.currentShot.preview_file_id &&
        this.currentShot.preview_file_id.length > 0
      )
    },

    getShotsRoute() {
      const route = {
        name: 'shots',
        params: {
          production_id: this.currentProduction.id
        },
        query: {
          search: this.shotSearchText
        }
      }
      if (this.currentEpisode) {
        route.name = 'episode-shots'
        route.params.episode_id = this.currentEpisode.id
      }
      return route
    },

    nbAssets() {
      let nbAssets = 0
      if (
        this.currentShot &&
        this.currentSection === 'casting' &&
        this.currentShot.castingAssetsByType
      ) {
        this.currentShot.castingAssetsByType.forEach((group) => {
          nbAssets += group.length
        })
      }
      return nbAssets
    }
  },

  methods: {
    ...mapActions([
      'clearSelectedTasks',
      'editShot',
      'loadShot',
      'loadShotCasting'
    ]),

    changeTab(tab) {
      this.selectedTab = tab
    },

    getCurrentShot() {
      return new Promise((resolve, reject) => {
        const shotId = this.route.params.shot_id
        const shot = this.shotMap.get(shotId) || null
        if (!shot) {
          return this.loadShot(shotId).then(resolve)
        } else {
          return resolve(shot)
        }
      })
    },

    onEditClicked() {
      this.modals.edit = true
    },

    confirmEditShot(form) {
      form.id = this.currentShot.id
      form.data.resolution = form.resolution
      form.data.max_retakes = form.max_retakes
      form.data.frame_in = form.frameIn
      form.data.frame_out = form.frameOut
      form.data.fps = form.fps
      this.loading.edit = true
      this.errors.edit = false
      this.editShot(form)
        .then(() => {
          this.loading.edit = false
          this.modals.edit = false
        })
        .catch((err) => {
          console.error(err)
          this.loading.edit = false
          this.errors.edit = true
        })
    },

    buildAssetRoute(asset) {
      let episodeId = asset.episode_id
      if (this.isTVShow && !episodeId) episodeId = 'main'
      const route = {
        name: 'asset',
        params: {
          production_id: this.currentProduction.id,
          asset_id: asset.asset_id
        }
      }
      return episodifyRoute(route, episodeId)
    },

    resetData() {
      this.casting.isLoading = true

      // Next tick is needed to wait for the episode change.
      this.$nextTick(() => {
        this.getCurrentShot()
          .then((shot) => {
            this.currentShot = shot
            return this.loadShotCasting(this.currentShot)
          })
          .then(() => {
            this.casting.isLoading = false
          })
          .catch((err) => {
            this.casting.isError = true
            this.casting.isLoading = false
            console.error(err)
          })
      })
    }
  },

  watch: {},

  metaInfo() {
    return {
      title: `${this.title} - Kitsu`
    }
  }
}
</script>

<style lang="scss" scoped>
.dark .page {
  background: $dark-grey-light;
  height: 100%;
  padding-bottom: 1em;
}

.dark .wrapper {
  background: $dark-grey-2;
}

.main-column {
  display: flex;
  flex-direction: column;
  background: var(--background-page);
  padding-bottom: 1em;
}

h2.subtitle {
  border-bottom: 0;
  margin-top: 0;
  margin-bottom: 0.5em;
  font-size: 1.5em;
}

.page-header {
  margin-top: calc(50px + 2em);
  margin-bottom: 0.8em;
  margin-left: 2em;
  margin-right: 1em;

  .entity-title {
    font-weight: 500;
  }
}

.infos {
  height: 350px;
  margin-bottom: 1em;
  margin-left: 1em;
  margin-right: 1em;

  .flexrow-item {
    align-self: flex-start;
    height: 100%;
    flex: 1;
  }
}

.shot-data {
  display: flex;
  flex: 1;
  flex-direction: column;
  margin: 0 1em 0 1em;
  max-height: 100%;
  overflow: hidden;
}

.shot-casting {
  overflow-y: auto;
}

.asset-link .thumbnail-picture {
  margin-bottom: 0.5em;
}

.asset-type {
  text-transform: uppercase;
  font-size: 1.2em;
  color: var(--text);
  margin-top: 2em;
  margin-bottom: 0.4em;
}

.asset-list {
  color: var(--text);
  display: flex;
  flex-wrap: wrap;
}

.asset-link {
  color: inherit;
  margin-right: 1em;
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 0.8em;
}

.asset-link div {
  max-width: 100px;
}

.asset-link span {
  word-wrap: break-word;
}

.field-label {
  font-weight: bold;
  width: 140px;
}

.page-header {
  align-items: center;
}

.data-list {
  max-width: 100%;
}

.back-link {
  padding-top: 3px;
}

.task-list {
  width: 100%;
}

.datatable-row {
  user-select: text;
}

.schedule {
  position: relative;
  height: 100%;

  .timelien-wrapper,
  .timeline {
    height: 100%;
  }

  .schedule-title {
    margin-bottom: 5px;
  }

  .wrapper {
    height: 100%;
    border-radius: 10px;
  }
}

.section-combo {
  width: 150px;

  .option-line {
    width: 150px;
  }
}

@media screen and (max-width: 768px) {
  .task-column {
    margin-bottom: 1em;
  }

  .column:first-child {
    margin-right: 0;
  }

  .entity-title {
    font-size: 1.3em;
    line-height: 1.5em;
  }
}

.tag-standby {
  background: $red;
  color: $white;
  margin-left: 1em;
  cursor: default;
  text-transform: uppercase;
}

.dark .tag-standby {
  background: $dark-red;
}
</style>
