<template>
    <div>
      <v-stepper v-model="this.stepper_step">
          <v-stepper-header>
              <v-stepper-step :color="stepper_color(1)" :complete="this.status > 0 && this.status < 10 || this.status == 11" :rules="[() => this.status != 10]" step="1">Approbation initiale</v-stepper-step>
              <v-divider></v-divider>
              <v-stepper-step :color="stepper_color(2)" :complete="this.status > 1 && this.status < 10 || this.status == 11" step="2">Slicing</v-stepper-step>
              <v-divider></v-divider>
              <v-stepper-step :color="stepper_color(3)" :complete="(this.status > 3 && this.status < 10 && this.status != 7)" :rules="[() => this.status != 11]" step="3">Impression</v-stepper-step>
              <v-divider></v-divider>
              <v-stepper-step :color="stepper_color(4)" step="4">Récupération</v-stepper-step>
          </v-stepper-header>

          <v-overlay v-model="reject_diag" hide-overlay>
            <v-card >
              <v-toolbar dark color="red">
                <v-btn icon dark @click="close_reject_dialog">
                  <v-icon>mdi-close</v-icon>
                </v-btn>
                <v-toolbar-title>Rejet de la demande d'impression</v-toolbar-title>
                <v-spacer></v-spacer>
              </v-toolbar>
              <form >
                <v-text-field style="padding: 20px;" v-model="rejectReason" label="Raison"></v-text-field>
                <v-btn color="red" class="mr-4" @click="reject_request">Rejeter</v-btn>
              </form>
            </v-card>
          </v-overlay>

          <v-stepper-items>
              <v-stepper-content step="1">
                  <v-card>
                    <v-icon>mdi-check-underline-circle</v-icon>&nbsp;Approuver ou rejeter la demande d'impression
                    <v-card-actions>
                    </v-card-actions>
                    <v-btn color="green" @click="approve_request()">Approuver</v-btn>
                    <v-btn color="red" @click="open_reject_dialog" >Refuser</v-btn>
                  </v-card>
              </v-stepper-content>

              <v-stepper-content step="2">
                <v-card>
                  <v-icon>mdi-cog-transfer</v-icon>&nbsp;Choisissez une méthode de slicing
                  <v-card-actions style="justify-content: center;">
                    <v-container>
                      <v-layout row>
                        <v-btn disabled><v-progress-circular indeterminate></v-progress-circular><v-icon>mdi-help-network</v-icon>Recherche d'un Slicer en ligne</v-btn>
                        <v-file-input @change="gcode_changed" id="file" justify="left" prepend-icon="mdi-upload-network"  dense small placeholder="Upload GCODE"></v-file-input>
                        <v-progress-circular indeterminate v-if="is_uploading_gcode"><v-icon>mdi-file-upload</v-icon></v-progress-circular>
                      </v-layout>
                    </v-container>
                  <!-- <v-btn color="primary" @click="e1 = 3">remove this button</v-btn> -->
                  </v-card-actions>
                </v-card>
              </v-stepper-content>

              <v-stepper-content step="3">
                <v-row>
                  <v-col>
                    <v-card>
                      <v-icon>mdi-cog-refresh</v-icon>&nbsp;Mode automatique
                      <v-card-actions>
                        <v-select
                          :items="all_queues"
                          v-model="queue"
                          label="File d'attente"
                          @change="update_queue"
                      ></v-select>
                      </v-card-actions>
                      <div>{{ position_text }}</div>
                      
                    </v-card>
                  </v-col>
                  <v-col>
                    <v-card>
                      <v-icon>mdi-cog-off</v-icon>&nbsp;Choix manuel
                      <v-card-actions>
                      </v-card-actions>
                      <v-btn color="green" @click="print_success">Impression réussie</v-btn>
                      <v-btn color="red" @click="approve_request" >Retour au slicing</v-btn>
                    </v-card>
                  </v-col>
                </v-row>
              </v-stepper-content>

              <v-stepper-content step="7">
                <v-card>
                  Fin de l'impression
                  <v-card-actions>
                  </v-card-actions>
                  <v-btn color="green" @click="print_success" >Impression réussie</v-btn>
                  <v-btn color="red" @click="set_to_print" >Ré-imprimer</v-btn>
                  
                </v-card>
              </v-stepper-content>

              <v-stepper-content step="4">
                  <v-card>
                    <v-icon>mdi-check-underline-circle</v-icon>&nbsp;Choix manuel
                    <v-card-actions>
                    </v-card-actions>
                    <v-btn color="green" @click="object_collected">Objet récupéré</v-btn>
                    <v-btn color="red" @click="set_to_print" >Ré-impression nécessaire</v-btn>
                    <v-btn color="grey" @click="close_request" >Cloturer la demande</v-btn>
                  </v-card>
                  
              </v-stepper-content>

              <v-stepper-content step="10">
                  <v-card>
                    <v-icon>mdi-alert</v-icon>&nbsp;La requête est rejetée par un opérateur
                    <v-card-actions>
                    </v-card-actions>
                    <v-btn color="green" @click="unreject()">Annuler le rejet</v-btn>
                  </v-card>            
              </v-stepper-content>

              <v-stepper-content step="11">
                <v-card>
                  Echec de l'impression
                  <v-card-actions>
                  </v-card-actions>
                  <v-btn color="red" @click="set_to_print" >Ré-imprimer</v-btn>
                  <v-btn color="grey" @click="close_request" >Cloturer la demande</v-btn>
                  
                </v-card>
              </v-stepper-content>

          </v-stepper-items>

      </v-stepper>
      <div>
        <p>Actions globales</p>
        <v-card>    
          <v-card-actions>
          </v-card-actions>
          <v-btn color="grey" @click="close_request">
            Annuler et cloturer la demande
          </v-btn>
        </v-card>
      </div>
    </div>
</template>

<script>
import UploadButton from 'vuetify-upload-button'
import axios from 'axios'
export default {
  name: 'ImpressionRequestInfos',
  mounted () {
    this.$store.dispatch('load_queues')
    .then((resp) => {
      this.do_reload()
    })
  },
  components: {
    'upload-btn': UploadButton
  },
  computed: {
    all_queues() {
      // console.log(this.$store.state.queues)
      return this.$store.state.queues
    }, 
    position_text() {
      return this.position == -1 ? "":"Position dans la queue: "+this.position
    },
    gcode_upload_progress() {
      return this.gcode_upload_progress_value
    }
    // request_object () {
    //   console.log(this.$store.state.admin_requests_dict[this.id])
    //   return this.$store.state.admin_requests_dict[this.id]
    // },
    // title () {
    //   return this.request_object.title
    // },
    // fullname () {
    //   return this.request_object.author
    // },
    // status () {
    //   return this.request_object.status
    // },
    // stepper_step () {
    //   return this.status < 3 ? this.status + 1 : this.status
    // }
  },
  methods: {
    update_queue() {
        axios.get("/requests/"+this.id+"/enqueue/"+this.queue.id)
    },
    object_collected() {
      this.$store.dispatch('update_request', {id: this.id, changes: {status: 6}}).then(() => {
        this.reload()
      })
    },
    close_request() {
      this.$store.dispatch('update_request', {id: this.id, changes: {status: 5}}).then(() => {
        this.reload()
      })
    },
    open_reject_dialog () {
      this.reject_diag = true
      this.$emit('stopReload')
    },
    close_reject_dialog () {
      this.reject_diag = false
      this.$emit('startReload')
    },
    do_reload() {
      var o = this.$store.state.admin_requests_dict[this.id]
      this.title = o.title
      this.fullname = o.fullname,
      this.status = o.status,
      this.stepper_step = this.status < 3 ? this.status + 1 : this.status
      this.position = o.queue_position
      // console.log(this.all_queues.filter((elem) => {return elem.id == o.queue}))
      setTimeout(() => {
        this.queue = o.queue ? this.all_queues.filter((elem) => {return elem.id == o.queue})[0] : null;
      }, 300)
    },
    reload () {
      this.$store.dispatch("update_requests", {status: [], no_load: false}).then((resp) => {
        this.do_reload()
      })
    },
    approve_request() {
      this.$store.dispatch('update_request', {id: this.id, changes: {status: 1}}).then(() => {
        axios.get("/requests/" + this.id + "/dequeue")
        .then((resp) => {
          this.reload()
        }).catch((error) => {
          console.log("[DEBUG] Could not dequue, ignoring")
          this.reload()
        })
      })
    },
    print_success() {
      this.$store.dispatch('update_request', {id: this.id, changes: {status: 4}}).then(() => {
        this.reload()
      })
    },
    set_to_print() {
      this.$store.dispatch('update_request', {id: this.id, changes: {status: 2}}).then(() => {
        this.reload()
      })
    },
    reject_request() {
      this.$store.dispatch('update_request', {id: this.id, changes: {status: 10, reject_message: this.rejectReason}}).then(() => {
        this.reload()
        this.close_reject_dialog()
      })
    },
    unreject() {
      this.$store.dispatch('update_request', {id: this.id, changes: {status: 0, reject_message: ''}}).then(() => {
        this.reload()
        this.close_reject_dialog()
      })
    },
    stepper_color (s) {
      return this.stepper_step > s ? 'green' : 'blue'
    },
    
    gcode_changed () {
      this.is_uploading_gcode = true
      this.gcode_upload_progress_value = 0
      let req_id = parseInt(this.id)
      var formData = new FormData();

      var progressHandler = function(progressEvent) {
        var percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        this.gcode_upload_progress_value = percentCompleted
      }

      formData.append("file", document.querySelector('#file').files[0]);
      axios.post(`/files/gcode/upload/${req_id}`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: progressHandler
      }).then((resp) => {
        this.is_uploading_gcode = false
        this.$store.dispatch('reload_request', this.id).then(() => {
          this.reload()
          console.log(resp)
        })
      }).catch((err) => {
        this.is_uploading_gcode = false
        this.$store.commit('display_error', 'Could not upload gcode: '+err)
        console.log(err)
        this.reload()
      })
    }
    
  },
  props: ['id'],
  data () {
    return {
      queue: null,

      gcode_upload_progress_value: 0,
      is_uploading_gcode: false,
      position: -1,
      title: '',
      fullname: '',
      status: 0,
      stepper_step: 0,

      reject_diag: false,
      rejectReason: '',
      files: null
    }
  }
}
</script>
