<template>
    <v-card max-width="500px">
        <v-card-title>{{ infos.name }}&nbsp;&nbsp;&nbsp;<v-btn :href="octo_path" target="_blank" small>octoprint</v-btn></v-card-title>
        <v-alert v-show="show_printer_ready" type="success"><b>Prêt à imprimer</b> <v-btn @click="clear_plate_flag_change">Undo</v-btn></v-alert>
        <v-alert v-show="!is_printer_enabled" type="warning"><center><b>L'imprimante est hors comission</b><br/>Aucune impression n'y sera démarée</center></v-alert>
        <v-alert type="error" v-if="is_errored">Printer error</v-alert>
        
        <v-row>
            <v-col>
                <v-card-subtitle  align="left" style="margin: 0">
                    <div>N°{{ infos.id }}&nbsp;|&nbsp;<code>{{ infos.version }}</code></div>
                    <div><v-icon :color="status_info.color">{{ status_info.icon }}</v-icon> <font :color="status_info.color">{{ infos.status }}</font></div>
                    
                    <div><font :color="temp_color"><v-icon :color="temp_color">mdi-thermometer-lines</v-icon> {{ temperature_display }}</font></div>
                    <div v-if="is_printing"><v-icon :color="time_color">mdi-clock-time-four</v-icon>&nbsp;<font :color="time_color">{{ progress_percent }}</font></div>
                </v-card-subtitle>
                <v-card-subtitle>
                    <div v-if="is_printing" style="align: center; border-style: solid; border-color: orange">
                        <u>En cours d'impression</u>
                        <div><v-icon>mdi-folder-cog</v-icon>{{ current_print }}</div>
                        <div><v-icon>mdi-account</v-icon>{{ current_author }}</div>
                    </div>
                </v-card-subtitle>
            </v-col>
                
            <v-col>
                <v-card-subtitle justify="right">
                    <v-select
                        :items="all_queues"
                        v-model="queues"
                        :multiple="true"
                        label="Files d'attente"
                        @change="update_queues"
                    ></v-select>
                    
                    <div style="margin: 5px; border-style: dotted; border-color: orange">
                        <u>Prochaine impression</u>
                        <div><v-icon>mdi-folder-cog</v-icon> {{ next_print }}</div>
                    </div>
                    
                </v-card-subtitle>
            </v-col>
        </v-row>
        
        <v-alert v-if="show_confirm_printer_status" type="warning"><b>Confirmer l'état de l'imprimante</b></v-alert>
        <div v-show="show_confirm_printer_status" style="margin: 24px; border-radius: 1px; border-style: dotted; border-color: orange;" align="center">
            Vérifiez que:
            <li><code>Le plateau est présent</code></li>
            <li><code>Le plateau est vide</code></li>
            <li><code>Le plateau est propre</code></li>
            <li><code>Le filament est chargé</code></li>
            <li><code>Le filament est suffisant</code></li>
        </div>
        <v-switch :disabled="clear_plate_flag" style="margin: 5px" v-show="show_confirm_printer_status" v-model="clear_plate_flag" @change="clear_plate_flag_change" label="Prêt à imprimer"></v-switch>
        
        <v-card-actions>
            <v-btn v-if="allow_control" @click="home">Home</v-btn>
            <v-btn v-if="is_printing" @click="cancel_print" color="red">Cancel</v-btn>
            <v-btn color="orange" @click="toggle_enabled">{{ toggle_enable_text }}</v-btn>
        </v-card-actions>
        <v-progress-linear height="5" striped :value="infos.printer_progress"></v-progress-linear>
    </v-card>
</template>
<script>
import axios from 'axios'
import utils from '@/utils/utils.js'
import { bus } from '../main'
export default {
    name: "PrinterCard",
    props: ['infos', 'bus'],
    data() {
        return {
            queues: [],
            previous_queus: [],
            clear_plate_flag: false,
            time_color: 'grey'
        }
    },
    updated() {

    },
    mounted() {
        bus.$on("refresh", this.refresh)
    },
    
    methods: {
        refresh() {
            this.set_selected_queues()
        },
        set_selected_queues() {
            // console.log(this.all_queues)
            let active_queues_ids = this.infos.queues.map((elem) => {return elem.id})
            let q = this.all_queues.filter((elem) => {return active_queues_ids.includes(elem.id)})
            this.queues = q;
            this.previous_queus = q;
        },
        update_queues() {
            // console.log(this.queues)
            
            let now_queues = this.queues.map((elem) => {return elem.id})
            let bef_queues = this.previous_queus.map((elem) => {return elem.id})
            this.previous_queus = this.queues
            // queue addition
            for(let q of now_queues) {
                if(!bef_queues.includes(q)) {
                    // q is a new queue id for the printer
                    axios.put("/printers/"+this.infos.id+"/queue/"+q)
                    return
                }
            }
            for(let q of bef_queues) {
                if(!now_queues.includes(q)) {
                    // q is queue id that was removed for the printer
                    axios.delete("/printers/"+this.infos.id+"/queue/"+q)
                }
            }
        },
        toggle_enabled() {
            this.puting_out = true
            axios.get("/printers/"+this.infos.id+"/action/toggle_enabled")
            .then(resp => {
                this.$store.dispatch("load_printers")
            })
        },
        clear_plate_flag_change() {
            console.log(this.clear_plate_flag)
            axios.get("/printers/"+this.infos.id+"/clear/"+(this.clear_plate_flag?0:1))
        },
        cancel_print() {
            axios.get("/printers/"+this.infos.id+"/action/cancel")
        },
        convert_time(d) {
            return utils.secondsToHms(d)
        },
        home() {
            axios.get('/printers/'+this.infos.id+'/home')
        }
        
    }, 
    computed: {
        current_author() {
            if (!this.infos.current_print) {
                return "???"
            }
            return this.infos.current_print.author
        },
        current_print() {
            if (!this.infos.current_print) {
                return "???"
            }
            return this.infos.current_print.title
        },
        next_print() {
            if(this.infos.next_print) {
                return '"' + this.infos.next_print.request.title + "\" par " +this.infos.next_print.request.author
            } else {
                return "Pas d'impression en attente"
            }
        },
        all_queues() {
            // console.log(this.$store.state.queues)
            return this.$store.state.queues
        },  
        octo_path() {
            return  'http://' + this.infos.config.hostname + ':' + this.infos.config.port
        },
        toggle_enable_text() {
            return this.is_printer_enabled?"Désactiver":"Activer"
        },
        is_printer_enabled() {
            return this.infos.enabled
        },
        show_printer_ready() {
            return !this.infos.clear_plate_flag && this.is_operational && this.is_printer_enabled && !this.is_printing
        },
        show_confirm_printer_status() {
            return this.infos.clear_plate_flag && this.is_operational && this.is_printer_enabled && !this.is_printing
        },
        progress_percent() {
            if (Math.ceil(this.infos.printer_progress) <= 1) {
                return "??% - ?? h, ?? min, ?? sec"
            }
            return Math.floor(this.infos.printer_progress) + "% " + this.convert_time(this.infos.remaining_print_time)
        },
        is_operational() {
            return this.infos.infos.state.flags.operational
        },
        is_printing() {
            return this.infos.infos.state.flags.printing
        },
        is_errored() {
            return this.infos.infos.state.flags.error
        },
        allow_control() {
            return !this.is_errored && this.is_operational && !this.is_printing
        },
        temperature_display() {
            return this.infos.infos.temperatures.tip + "/" + this.infos.infos.temperatures.bed + " °C"
        },
        status_info() {
            if (this.is_errored) {
                return {'icon': "mdi-alert-circle", 'color': 'red'}
            }else if (this.is_printing) {
                return {'icon': "mdi-printer-3d-nozzle", 'color': 'yellow' }
            }else if (this.is_operational) {
                return {'icon': "mdi-check-circle", 'color': 'green'}
            }else {
                return {'icon': "mdi-alert-circle", 'color': 'red'}
            }
        },
        temp_color() {
            if (this.infos.infos.temperatures.tip > 300 || this.infos.infos.temperatures.bed > 70) {
                return "red"
            } else if (this.infos.infos.temperatures.tip > 50 || this.infos.infos.temperatures.bed > 30) {
                return "orange"
            } else {
                return "cyan"
            }
        }
    }
}
</script>