<template>
<div class="row">
    <div class="col">
        <div class="scroll">
            <table class="table mb-5" ref="table">
                <thead>
                <tr>
                    <th> </th>
                    <th>Name</th>
                    <th>Caption</th>
                    <th>Type</th>
                    <th></th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="row, n in rows" @mousedown="setCurrentRow(row)" :class="row==currentRow?'active-row':''">
                    <td>
                    <span v-if="row==currentRow">
                        <CopyPasteMenu :row="row" :clipboard="clipboard" @copy="doAction('copy', $event)" @paste="doAction('paste', $event)">⯈</CopyPasteMenu>
                    </span>
                    <span v-else>&nbsp;&nbsp;</span>
                    </td>
                    <td><input v-model="row.name" ref="name" @focus="currentField='name'" class="form-control form-control-sm"></td>
                    <td><input v-model="row.caption" ref="caption" @focus="currentField='caption'" class="form-control form-control-sm"></td>
                    <td>{{ feederTypes[row.type].name }}</td>
                    <td><input v-model="row.active" ref="active" @focus="currentField='active'" type="checkbox" class="form-control form-control-sm" title="Active"></td>
                    <th nowrap>
                        <button class="btn btn-sm btn-outline-secondary me-1" @click="$emit('up', row)">⯅</button>
                        <button class="btn btn-sm btn-outline-secondary me-1" @click="$emit('down', row)">⯆</button>
                        <button class="btn btn-sm btn-outline-secondary btn-danger" @click="$emit('delete', row)">⮿</button>
                    </th>
                </tr>
                </tbody>
            </table>
            <div class="text-end">
                <button @click="$emit('add')" class="btn btn-sm btn-outline-secondary">Add feeder</button>
            </div>
        </div>
    </div>
    <div class="col">
        <div class="scroll">
            <div class="card" v-if="isCurrent">
                <div class="card-header">Feeder {{ currentRow.name }} (#{{ currentRow.id }})</div>
                <div class="card-body">

                    <div class="mb-3">
                        <label class="form-label">Name</label>
                        <div class="row mb-2">
                            <div class="col">
                                <input v-model="currentRow.name" type="text" class="form-control form-control-sm">
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Caption</label>
                        <div class="row mb-2">
                            <div class="col">
                                <input v-model="currentRow.caption" type="text" class="form-control form-control-sm">
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Type</label>
                        <div class="row mb-2">
                            <div class="col">
                                <select v-model="currentRow.type" class="form-control form-control-sm">
                                    <option :value="item.id" v-for="item in feederTypes">{{ item.name }}</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <span v-if="currentRow.type==0">
                    <div class="mb-3">
                        <label class="form-label">Position</label>
                        <div class="row mb-2">
                            <div class="col">
                                X: <input v-model="currentRow.pos.x" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col">
                                Y: <input v-model="currentRow.pos.y" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col">
                                Z: <input v-model="currentRow.pos.z" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col-auto">
                                <button class="btn btn-sm btn-outline-secondary btn-danger me-1 mt-3" @click="setFeederPosCAM(currentRow)" title="Set current position of camera (x, y)">⛶</button>
                                <button class="btn btn-sm btn-outline-secondary btn-danger me-1 mt-3" @click="setFeederPos(currentRow)" title="Set current position of nozzle (x, y, z)">🞊</button>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Step</label>
                        <div class="row mb-2">
                            <div class="col">
                                X: <input v-model="currentRow.step.x" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col">
                                Y: <input v-model="currentRow.step.y" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col">
                                Z: <input v-model="currentRow.step.z" type="text" class="form-control form-control-sm">
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="row mb-2">
                            <div class="col">
                                Capacity <input v-model="currentRow.capacity" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col">
                                Current <input v-model="currentRow.current" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col">
                                <button class="btn btn-sm btn-outline-secondary btn-danger me-1 mt-3" @click="currentRow.current=0">Reset</button>
                            </div>
                        </div>
                    </div>
                    
                    </span>

                    <span v-if="currentRow.type==1">
                        <div class="mb-3">
                        <label class="form-label">Path points</label>
                        <div class="row mb-2">
                            <div class="col">

                                <FeedersPathPointsTable
                                    :rows="currentRow.pathPoints"
                                    :currentRow="currentPoint"
                                    @add="addPathPoint($event)"
                                    @set="currentPoint=$event"
                                    @setPos="setPointPos($event)"
                                    @delete="rowDelete(currentRow.pathPoints, $event)">
                                </FeedersPathPointsTable>

                            </div>
                        </div>
                        </div>
                    </span>


                    <span v-if="currentRow.type==2">
                    <div class="mb-3">
                        <label class="form-label">Position (center)</label>
                        <div class="row mb-2">
                            <div class="col">
                                X: <input v-model="currentRow.pos.x" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col">
                                Y: <input v-model="currentRow.pos.y" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col">
                                Z: <input v-model="currentRow.pos.z" type="text" class="form-control form-control-sm">
                            </div>
<!--
                            <div class="col">
                                Radius: <input v-model="currentRow.pos.radius" type="text" class="form-control form-control-sm">
                            </div>
-->
                            <div class="col-auto">
                                <button class="btn btn-sm btn-outline-secondary btn-danger me-1 mt-3" @click="setFeederPosCAM(currentRow)" title="Set current position of camera (x, y)">⛶</button>
                                <button class="btn btn-sm btn-outline-secondary btn-danger me-1 mt-3" @click="setFeederPos(currentRow)" title="Set current position of nozzle (x, y, z)">🞊</button>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Size</label>
                        <div class="row mb-2">
                            <div class="col">
                                Width X: <input v-model="currentRow.pos.wx" type="text" class="form-control form-control-sm">
                            </div>
                            <div class="col">
                                Width Y: <input v-model="currentRow.pos.wy" type="text" class="form-control form-control-sm">
                            </div>
                        </div>
                    </div>                    
                    </span>


                    <div class="mb-3">
                        <label class="form-label">Elements height</label>
                        <div class="row mb-2">
                            <div class="col">
                                <input v-model="currentRow.elementHeight" type="number" step="0.01" class="form-control form-control-sm">
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Nozzle</label>
                        <div class="row mb-2">
                            <div class="col">
                                <select v-model="currentRow.nozzle" class="form-control form-control-sm">
                                    <option :value="item.id" v-for="item in settings.nozzles">{{ item.name }}</option>
                                </select>
                                <div class="form-text">Specify Nozzle to pick up element</div>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Case</label>
                        <div class="row mb-2">
                            <div class="col">
                                <select v-model="currentRow.case" class="form-control form-control-sm" @change="drawSMDCase()">
                                    <option :value="item.name" v-for="item in cases">{{ item.name }}</option>
                                </select>
                                <canvas ref="smdCase" width="64" height="64" style="border: silver solid 1px"></canvas>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Orientation in the feeder</label>
                        <div class="row mb-2">
                            <div class="col">
                                <input v-model="currentRow.caseRotate" type="number" step="0.125" class="form-control form-control-sm" @change="drawSMDCase()">
                            </div>
                            <div class="form-text">Sets elements orientation in the feeder</div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label" for="posCorrection">Correct the element's position after pick</label>
                        <div class="row mb-2">
                            <div class="col">
                                <div class="form-check form-switch">
                                    <input v-model="currentRow.posCorrection" class="form-check-input" type="checkbox" role="switch" id="posCorrection">
                                </div>
                            </div>
                            <div class="form-text">Uses bottom camera to correct position of element after pick</div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Active</label>
                        <div class="row mb-2">
                            <div class="col">
                                <div class="form-check form-switch">
                                    <input v-model="currentRow.active" class="form-check-input" type="checkbox" role="switch" id="posCorrection">
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>

            <div class="card mt-1" v-if="isCurrent">
                <div class="card-header">Actions</div>
                <div class="card-body">
                    <div>
                        <button :disabled="disabled" class="btn btn-sm btn-outline-secondary m-1" @click="$emit('pickFromFeeder', currentRow)">Pick element from Feeder</button>
                        <button :disabled="disabled" class="btn btn-sm btn-outline-secondary m-1" @click="$emit('adjPosition')">Adjust position of Picked element</button>
                        <button :disabled="disabled" class="btn btn-sm btn-outline-secondary m-1" @click="$emit('dropIntoBasket')">Drop Picked element into Basket</button>
                    </div>
                    <div>
                        <button :disabled="disabled" class="btn btn-sm btn-outline-secondary m-1" @click="$emit('goToFeeder', currentRow)">Jog Nozzle to to Feeder position</button>
                        <button :disabled="disabled" class="btn btn-sm btn-outline-secondary m-1" @click="$emit('goToFeederCam', currentRow)">Jog Camera to to Feeder position</button>
                    </div>

                    <div>

                        <PopupMenu>
                            <template v-slot:menubutton>
                                <button :disabled="disabled" class="btn btn-sm btn-outline-secondary m-1 dropdown-toggle">Manual Adjust feeder's position by top Camera</button>
                            </template>
                            <template v-slot:menuitems>
                                <PopupMenuItem :disabled="disabled" @click="adjFiderPosByCamPos(currentRow, 'x')">X</PopupMenuItem>
                                <PopupMenuItem :disabled="disabled" @click="adjFiderPosByCamPos(currentRow, 'y')">Y</PopupMenuItem>
                                <PopupMenuItem :disabled="disabled" @click="adjFiderPosByCamPos(currentRow, 'xy')">Both</PopupMenuItem>
                            </template>
                        </PopupMenu>

                        <button :disabled="disabled || (currentRow.type==2)" class="btn btn-sm btn-outline-secondary m-1" @click="$emit('adjFeederPositionCV', currentRow)">Adjust Feeder's position by CV</button>

                    </div>

                </div>
            </div>

        </div>
    </div>
</div>
</template>

<script>
    import tableMixin from '../js/rows_table.js'
    import machineState from '../js/machine_state.js'
    import FeedersPathPointsTable from "../components/FeedersPathPointsTable.vue"
    import CopyPasteMenu from "../components/CopyPasteMenu.vue"
    import PopupMenu from "../components/PopupMenu.vue"
    import PopupMenuItem from "../components/PopupMenuItem.vue"
    import deepMerge from '../js/deep_merge.js'

    export default {
        mixins: [tableMixin, machineState, deepMerge],
        props: {
            settings: Object,
            cases: Object,
            feederTypes: Object,
            machineState: Object,
            machinePos: Object,
            disabled: Boolean
        },
        components: {
            FeedersPathPointsTable, CopyPasteMenu, PopupMenu, PopupMenuItem
        },
        data: function () {
            return {
                currentField: 'name',
                currentPoint: this.currentPoint,
                clipboard: this.clipboard
            }
        },
        computed: {
            isCurrent() {
                return this.currentRow && (this.rows.indexOf( this.currentRow) > -1)
            }
        },
        methods: {
            addPathPoint(event) {
                this.currentRow.pathPoints.push({x:0, y:0, z:0, pick: false})
            },
            setFeederPos(feeder) {
                if (this.machineStateIsOK() == true) {
                    feeder.pos.x = this.machinePos.x
                    feeder.pos.y = this.machinePos.y
                    feeder.pos.z = this.machinePos.z
                }
            },
            setFeederPosCAM(feeder) {
                if (this.machineStateIsOK() == true) {
                    feeder.pos.x = (parseFloat(this.machinePos.x) + parseFloat(this.settings.cams[0].offset.x)).toFixed(3)
                    feeder.pos.y = (parseFloat(this.machinePos.y) + parseFloat(this.settings.cams[0].offset.y)).toFixed(3)
                    //feeder.pos.z = this.machinePos.z                    
                }
            },
            setPointPos(pathPoint) {
                if (this.machineStateIsOK() == true) {
                    pathPoint.x = this.machinePos.x
                    pathPoint.y = this.machinePos.y
                    pathPoint.z = this.machinePos.z
                }
            },

            adjFiderPosByCamPos(feeder, axis) {
                if (this.machineStateIsOK() == true) {
                    
                    // Liner                    
                    if (feeder.type == 0) {
                        if ((axis == 'x') || (axis == 'xy')) {
                            feeder.pos.x = parseFloat(this.machinePos.x) + parseFloat(this.settings.cams[0].offset.x)
                        }
                        if ((axis == 'y') || (axis == 'xy')) {
                            feeder.pos.y = parseFloat(this.machinePos.y) + parseFloat(this.settings.cams[0].offset.y)
                        }
                    }
                    
                    // Push-pull
                    if (feeder.type == 1) {
                        let pickPoint
                        for (let point of feeder.pathPoints) {
                            if (point.pick == true) {
                                pickPoint = point
                            }
                        }

                        if (pickPoint) { // pick point is found
                            let currentX = parseFloat(this.machinePos.x) + parseFloat(this.settings.cams[0].offset.x)
                            let currentY = parseFloat(this.machinePos.y) + parseFloat(this.settings.cams[0].offset.y)

                            let dX = currentX - pickPoint.x
                            let dY = currentY - pickPoint.y

                            for (let point of feeder.pathPoints) {
                                if ((axis == 'x') || (axis == 'xy')) {
                                    point.x = (parseFloat(point.x) + parseFloat(dX)).toFixed(3)
                                }
                                if ((axis == 'y') || (axis == 'xy')) {
                                    point.y = (parseFloat(point.y) + parseFloat(dY)).toFixed(3)
                                }
                            }
                        }

                    }

                }
            },

            drawSMDCase() {
                let canvas = this.$refs['smdCase']
                let ctx = canvas.getContext('2d')

                let width = canvas.width
                let height = canvas.height

                // Clear Canvas
                ctx.clearRect(0, 0, width, height)

                if (this.$refs['smdCase']) {
                    let caseName = this.currentRow.case

                    for (let SMDcase of this.cases) {
                        if (SMDcase.name == caseName) {

                            const img = new Image();
                            img.src = SMDcase.src

                            img.onload = ()=> {
                                let cx = width / 2
                                let cy = height / 2

                                let newWidth = width * 0.7 // 70% of width
                                let newHeight = img.height * (newWidth/img.width)

                                let imgX = cx - newWidth / 2
                                let imgY = cy - newHeight / 2

                                // Rotate canvas
                                let SMDRotate = 2*Math.PI * this.currentRow.caseRotate
                                ctx.translate(cx, cy)
                                ctx.rotate(-SMDRotate)
                                ctx.translate(-cx, -cy)

                                // Draw SVG on Canvas
                                ctx.drawImage(img, imgX, imgY, newWidth, newHeight)

                                // Rotate canvas back
                                ctx.translate(cx, cy)
                                ctx.rotate(SMDRotate)
                                ctx.translate(-cx, -cy)

                                // Renter canvas
                                ctx.stroke()                        
                            };
                        }
                    }
                }
            },

            doAction(event, row) {
                if (event == 'copy') {
                    this.clipboard = Object.assign({}, row)
                }

                if (event == 'paste') {
                    this.clipboard.id = row.id
                    row = this.deepMerge(row, this.clipboard)
                }
            }
        },

        watch: {
            currentRow() {
                clearTimeout(this.timerId)
                this.timerId = setTimeout(() => { this.drawSMDCase() }, 200)
            }
        }

    }
</script>

<style>
.active-row {
    background-color: #F6F6F6;
}

.settings .scroll {
    max-height: 70vh;
    overflow: auto;
}

.project .scroll {
    max-height: 60vh;
    overflow: auto;
}
</style>