<template>
    <div>
        <input type="file" ref="openFile" accept=".csv" style="display:none" @change="importFile()" />

        <DialogWindow title="Open" width="800" height="520" :number="0" v-show="showWindow[0]" @close="closeDialogOpenProject()">
            <div style="max-height: 400px; overflow-y: auto;">
                <table class="table" ref="table">
                    <thead>
                        <tr>
                            <th></th>
                            <th>Projects</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="item in projectsList" @click="inpuValue=item" @dblclick="project.name=item; closeDialogOpenProject(); loadProject()" :class="inpuValue==item?'active-row':''">
                            <td width="2">
                                <span v-if="inpuValue==item">⯈</span>
                                <span v-else>&nbsp;&nbsp;</span>
                            </td>
                            <td>{{ item }}</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="float-end" style="position: absolute; bottom: 0px;">
                <button :disabled="loading || (projectsList.indexOf(inpuValue) == -1)" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="project.name=inpuValue; closeDialogOpenProject(); loadProject()">Open</button>
                <button :disabled="loading" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="closeDialogOpenProject()">Cancel</button>
            </div>
        </DialogWindow>

        <DialogWindow title="Save as..." width="800" height="520" :number="1" v-show="showWindow[1]" @close="closeDialogSaveAs()">
            <input v-model="inpuValue" class="form-control form-control-sm" type="text" @keyup.enter="project.name=inpuValue; closeDialogSaveAs(); saveProject()">
            <div>
                <select size="20" disabled class="form-control">
                    <option v-for="item in projectsList">{{ item }}</option>
                </select>
            </div>
            <div class="float-end" style="position: absolute; bottom: 0px;">
                <button :disabled="loading || (projectsList.indexOf(inpuValue) > -1)" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="project.name=inpuValue; closeDialogSaveAs(); saveProject()">Save</button>
                <button :disabled="loading" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="closeDialogSaveAs()">Cancel</button>
            </div>
        </DialogWindow>

        <DialogWindow title="Projects manager" width="800" height="520" :number="2" v-show="showWindow[2]" @close="closeDialogProjectsManager()">
            <div style="max-height: 400px; overflow-y: auto;">
                <table class="table" ref="table">
                    <thead>
                        <tr>
                            <th></th>
                            <th>Project</th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="item in projectsList" @click="inpuValue=item" :class="inpuValue==item?'active-row':''">
                            <td width="2">
                                <span v-if="inpuValue==item">⯈</span>
                                <span v-else>&nbsp;&nbsp;</span>
                            </td>
                            <td>{{ item }}</td>
                            <td width="220">
                                <button :disabled="loading" type="button" class="btn btn-sm btn-outline-secondary me-1" @click="project.name=item; closeDialogProjectsManager(); loadProject()">Open</button>
                                <button :disabled="loading" type="button" class="btn btn-sm btn-outline-secondary me-1" @click="renameProject(item)">Rename</button>
                                <button :disabled="loading" type="button" class="btn btn-sm btn-outline-secondary me-1" @click="deleteProject(item)">Delete</button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
            <div class="float-end" style="position: absolute; bottom: 0px;">
                <button :disabled="loading" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="closeDialogProjectsManager()">Cancel</button>
            </div>
        </DialogWindow>

        <div class="project-name">
            <div class="row">
                <div class="col">
                    Project: <b>{{ project.name }}</b>
                </div>
                <div class="col-auto">
                    <button :disabled="loading || dialogIsOpened" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="newProject()">New...</button>
                    <button :disabled="loading || dialogIsOpened" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="openDialogOpenProject()">Open...</button>
                    <button :disabled="loading || dialogIsOpened" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="saveProject()">Save Project</button>
                    <button :disabled="loading || dialogIsOpened" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="openDialogSaveAs()">Save as...</button>                
                    <button :disabled="loading || dialogIsOpened" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="openDialogProjectsManager()">Projects manager...</button>                
                </div>
            </div>
        </div>

        <ul class="nav nav-tabs">
            <li class="nav-item">
                <a :class="'nav-link' + (tab==0?' active':'')" @click="tab=0">Feeders</a>
            </li>
            <li class="nav-item">
                <a :class="'nav-link' + (tab==1?' active':'')" @click="tab=1">Elements</a>
            </li>
            <li class="nav-item">
                <a :class="'nav-link' + (tab==2?' active':'')" @click="tab=2">PCB</a>
            </li>
            <li class="nav-item">
                <a :class="'nav-link' + (tab==3?' active':'')" @click="tab=3">Job</a>
            </li>
        </ul>

        <div v-show="tab==0" class="row mt-2">
            <div class="col project">
                <FeedersSettings
                    :settings="settings"
                    :cases="cases"
                    :machineState="machineState"
                    :machinePos="machinePos"
                    :feeders="project.feeders"
                    :disabled="disabled"
                    :loading="loading"
                    @adjFeederPositionCV="pnpAdjFeederPositionCV($event)"
                    @goToFeeder="pnpGoToFeeder($event)"
                    @goToFeederCam="pnpGoToFeederCam($event)"
                    @pickFromFeeder="pnpPickFromFeeder($event)"
                    @adjPosition="pnpAdjPosition($event)"
                    @dropIntoBasket="pnpDropIntoBasket($event)"
                    @saveFeeders="saveFeeders()">
                </FeedersSettings>
                <button type="button" class="btn btn-sm btn-outline-secondary m-1" @click="importFeeder()">Import from settings</button>
                <button :disabled="disabled" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="pnpAdjFeedersPositionCV()">Adjust position of all active feeders using CV</button>
            </div>
        </div>

        <div v-show="tab==1" class="row mt-2">
            <div class="col">
                <ElementsTable
                    :rows="project.elements"
                    :currentRow="currentElement"
                    :feeders="project.feeders"
                    :settings="settings"
                    :machineState="machineState"
                    :machinePos="machinePos"
                    :disabled="disabled"
                    @goToFeeder="pnpGoToFeeder($event)"
                    @goToFeederCam="pnpGoToFeederCam($event)"
                    @goToElement="goToElement($event)"
                    @goToElementCam="goToElementCam($event)"
                    @placeElement="placeElement($event)"
                    @sortElements="sortElements($event)"
                    @runFrom="runFrom($event)"
                    @add="addElement()"
                    @import="importElements()"
                    @set="setCurrentElement($event)"
                    @up="rowUp(project.elements, $event)"
                    @down="rowDown(project.elements, $event)"
                    @delete="rowDelete(project.elements, $event)">
                </ElementsTable>
            </div>
        </div>

        <div v-show="tab==2" class="row mt-2">
            <div class="col">
                <div class="card mb-4">
                    <div class="card-header">Manual position Adjustment</div>
                    <div class="card-body">
                        <div>
                            <button :disabled="disabled" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="jogFirstElement()">Jog Camera to first elment</button>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Offset of first element (manual correction)</label>
                            <div class="row mb-2">
                                <div class="col">
                                    X: <input v-model="project.pcb.pos.x" type="number" class="form-control form-control-sm" step="0.01">
                                </div>
                                <div class="col">
                                    Y: <input v-model="project.pcb.pos.y" type="number" class="form-control form-control-sm" step="0.01">
                                </div>
                              
                                <div class="col-auto">
                                    <button class="btn btn-sm btn-outline-secondary btn-danger me-1 mt-3" @click="setPCBPosCam()" title="Set current position of camera">⛶</button>
                                    <button class="btn btn-sm btn-outline-secondary btn-danger me-1 mt-3" @click="setPCBPos()" title="Set current position of nozzle">🞊</button>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">PCB thickness</label>
                            <input v-model="project.pcb.pos.z" type="number" class="form-control form-control-sm" step="0.01">
                        </div>

                    </div>
                </div>


                <div class="card">
                    <div class="card-header">Automatically position Adjustment</div>
                    <div class="card-body">
                        <div class="mb-3">
                            <button :disabled="disabled" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="adjPCBPositionCV()">Adjust PCB Offsets by CV</button>
                            <div>(fiducials are need)</div>
                        </div>
                    </div>
                </div>

            </div>
        </div>

        <div v-show="tab==3" class="row mt-2">
            <div class="col">
                <div class="card mb-4">
                    <div class="card-header">Before Run Adjustment</div>
                    <div class="card-body">
                        <div>
                            <button :disabled="disabled" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="pnpAdjFeedersPositionCV()">Adjust position of all active feeders using CV</button>
                        </div>
                        <div>
                            <button :disabled="disabled" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="adjPCBPositionCV()">Adjust PCB Offsets by CV</button> (fiducials are need)
                        </div>
                    </div>
                </div>


                <div class="card">
                    <div class="card-header">Run</div>
                    <div class="card-body">
                        <button :disabled="disabled" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="run()">Start</button>

                        <button :disabled="pnpProcessing.runFlag==false" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="pause()">
                            <span v-if="pnpProcessing.pauseFlag==false">Pause</span>
                            <span v-else>Resume</span>
                        </button>

                        <button :disabled="pnpProcessing.runFlag==false" type="button" class="btn btn-sm btn-outline-secondary m-1" @click="stop()">Stop</button>

                        <div v-if="pnpProcessing.message!=''" class="alert alert-success" role="alert">
                            {{ pnpProcessing.message }}
                            <span v-if="this.pnpProcessing.runFlag==false">
                                <button type="button" class="btn btn-sm btn-outline-secondary m-1" @click=findElement()>Find Element in elements list</button>
                                <button type="button" class="btn btn-sm btn-outline-secondary m-1" @click=runFrom(this.pnpProcessing.element)>Resume Job from this element</button>
                            </span>
                        </div>

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

    </div>
</template>

<script>
    import rowsEdit from '../js/rows_edit.js'
    import machineState from '../js/machine_state.js'
    import FeedersSettings from "../components/FeedersSettings.vue"
    import ElementsTable from "../components/ElementsTable.vue"
    //import InputSelect from "../components/InputSelect.vue"
    import DialogWindow from "../components/DialogWindow.vue"
    import { alert, confirm, prompt} from '../js/dialogs.js'

    export default {
        mixins: [rowsEdit, machineState],
        components: {
            FeedersSettings, ElementsTable, /*InputSelect,*/ DialogWindow
        },
        data() {
            return {
                tab: 0,
                currentElement: this.currentElement,
                showWindow:[false, false],
                inpuValue: ""
            }
        },
        props: {
            project: Object,
            projects_list: Object,
            settings: Object,
            cases: Object,
            machineState: Object,
            machinePos: Object,
            pnpProcessing: Object,
            default_feeders: Object,
            disabled: Boolean,
            loading: Boolean,
        },
        computed: {
            projectsList() {
                if (this.projects_list) {
                    let result = []
                    for (let item of this.projects_list) {
                        result.push(item.split('.').slice(0, -1).join('.'))
                    }
                    return result
                }
            },
            dialogIsOpened() {
                return (this.showWindow.indexOf(true) > -1)
            }

        },
        methods: {
            importFeeder() {
                confirm('The Feeders of this project will be replaced by Default Feeders settings. Do you want import default Feeders?', 'Confirm').then((res)=> {
                    if (res == true) {
                        this.project.feeders = JSON.parse(JSON.stringify(this.default_feeders))
                    }
                })
            },
            pnpAdjFeederPositionCV(event) {
                this.$emit('adjFeederPositionCV', event)
            },
            pnpAdjFeedersPositionCV() {
                this.$emit('adjFeedersPositionCV', this.project.feeders)
            },
            setCurrentElement(event) {
                this.currentElement = event
                for (let feeder of this.project.feeders) {
                    if (feeder.id == event.feeder) {
                        let a = parseFloat(feeder.caseRotate) + parseFloat(event.pos.a)
                        this.$emit('setSMDCase', {'case':feeder.case, 'rotate':a})
                    }
                }
            },
            pnpGoToFeeder(event) {
                this.$emit('goToFeeder', event)
            },
            pnpGoToFeederCam(event) {
                this.$emit('goToFeederCam', event)
            },
            pnpPickFromFeeder(event) {
                this.$emit('pickFromFeeder', event)
            },
            pnpAdjPosition(event) {
                this.$emit('adjPosition', event)
            },
            pnpDropIntoBasket(event) {
                this.$emit('dropIntoBasket', event)
            },
            runFrom(event) {
                this.$emit('runFrom', event)
                this.tab = 3
            },
            saveFeeders() {
                confirm('Attention! This feeders set will saved when You Save Project! You can set this feeders set as default. Do You want to set this Feeders set as default?', 'Warning').then((res)=> {
                    if (res == true) {
                        confirm('Do You want to set this Feeders set as default? Are You sure?', 'Confirm').then((res)=> {
                            if (res == true) {
                                this.$emit('setFeeders')
                            }
                        })
                    }
                })
            },

            openDialogOpenProject() {
                this.showWindow[0] = true
            },
            closeDialogOpenProject() {
                this.showWindow[0] = false
            },
            openDialogSaveAs() {
                this.inpuValue = this.project.name
                this.showWindow[1] = true
            },
            closeDialogSaveAs() {
                this.showWindow[1] = false
            },

            openDialogProjectsManager() {
                this.showWindow[2] = true
            },
            closeDialogProjectsManager() {
                this.showWindow[2] = false
            },

            newProject() {
                confirm('Attention! All changes of current project will lost. Do You want to create new Project?', 'Confirm').then((res)=> {
                    if (res == true) {
                        this.$emit('newProject')
                    }
                })
            },
            loadProject() {
                if (this.projectsList.indexOf(this.project.name) != -1) {
                    this.$emit('loadProject')
                } else {
                    alert("Can't load project \"" + this.project.name + "\". The project is missing.", "Warning", 'warning')
                }
            },
            saveProject() {
                if (this.project.name != 'New Project') {
                    this.$emit('saveProject')
                } else {
                    this.openDialogSaveAs()
                }
            },
            async renameProject(projectName) {
                let newName = await prompt("Please enter new project name:", "Rename", projectName)
                if ( (newName !== null) && (newName != false) ) {
                    if (this.projectsList.indexOf(newName) == -1) {
                        this.$emit('renameProject', {name: projectName, newName: newName})
                    } else {
                        alert("Can't rename the Project. A project with the specified name already exists!", 'Warning', 'warning')
                    }
                }
            },
            deleteProject(projectName) {
                confirm('Do You want to delete project "'+projectName+ '"?', 'Confirm').then((res)=> {
                    if (res == true) {
                        this.$emit('deleteProject', projectName)
                    }
                })                
            },

            goToElement(event) {
                this.$emit('goToElement', event)
            },
            goToElementCam(event) {
                this.$emit('goToElementCam', event)
            },
            placeElement(event) {
                this.$emit('placeElement', event)
            },
            getNextElementId() {
                let id = 1
                for (let row of this.project.elements) {
                    if (row.id >= id) {
                        id = row.id + 1
                    }
                }
                return id
            },
            addElement() {
                let id = this.getNextElementId()
                this.project.elements.push(
                    {
                        id: id,
                        name: "SMD " + id.toString(),
                        caption: "",
                        feeder: 0,
                        pos: {x:0, y:0, a:0},
                        active: true
                    }
                )
                this.currentElement = this.project.elements[this.project.elements.length-1]
            },
            getFeederById(feederId) {
                for (let feeder of this.project.feeders) {
                    if (feeder.id == feederId) {
                        return feeder
                    }
                }
                return null
            },
            /*
            getNozzleById(nozzleId) {
                for (let nozzle of this.settings.nozzles) {
                    if (nozzle.id == nozzleId) {
                        return nozzle
                    }
                }
                return null
            },
            */
            sortElements(sortBy) {
                let rows = this.project.elements.slice()
                rows = rows.sort((aRow, bRow) => {
                    let a, b

                    if (sortBy.field == 'feeder') {
                        a = parseFloat(aRow.feeder)
                        b = parseFloat(bRow.feeder)
                    }
                    if (sortBy.field == 'nozzle') {
                        let feederA = this.getFeederById(aRow.feeder)
                        let feederB = this.getFeederById(bRow.feeder)
                        if (feederA != null) {
                            a = parseFloat(feederA.nozzle)
                        }
                        if (feederB != null) {
                            b = parseFloat(feederB.nozzle)
                        }
                    }
                    if (sortBy.field == 'x') {
                        a = parseFloat(aRow.pos.x)
                        b = parseFloat(bRow.pos.x)
                    }
                    if (sortBy.field == 'y') {
                        a = parseFloat(aRow.pos.y)
                        b = parseFloat(bRow.pos.y)
                    }

                    if (sortBy.order=='up') {
                        return (a < b ? -1 : (a > b ? 1 : 0))
                    } else {
                        return (b < a ? -1 : (b > a ? 1 : 0))
                    }
                })

                this.project.elements = rows
            },
            importElements() {
                this.$refs.openFile.click()
            },
            importFile() {

                function parseTextValue (fieldValue) {
                    fieldValue = fieldValue.replace(/[\"]/g, '')
                    return fieldValue
                }
                function parseFloatValue (fieldValue) {
                    fieldValue = parseFloat(fieldValue.replace(/[^0-9,\.]/g, ''))
                    return fieldValue
                }

                let file = this.$refs.openFile.files[0]

                if (file) {
                    let reader = new FileReader();
                    reader.readAsText(file, "UTF-8");
                    reader.onload = (evt)=> {
                        let lines = evt.target.result.split("\n")
                        if (lines.length > 0) {
                            // Get a fields names
                            let fields = lines[0].split("\t")
                            let fieldName = {}
                            let n = 0
                            for (let field of fields) {
                                fieldName[field] = n
                                n++
                            }

                            let tableX = parseFloat(this.settings.table.pos.x)
                            let tableY = parseFloat(this.settings.table.pos.y)

                            // get Elemens
                            n = 0
                            for (let line of lines) {
                                if (n > 0) {
                                    let cols = line.split("\t")
                                    if (cols.length > 1) {
                                        let comment = parseTextValue(cols[fieldName['Comment']])
                                        let feederId = 0

                                        // Find fedder
                                        for (let feeder of this.project.feeders) {
                                            if (feeder.caption.toUpperCase() == comment.toUpperCase()) {
                                                feederId = feeder.id
                                            }
                                        }

                                        

                                        this.project.elements.push(
                                            {
                                                id: this.getNextElementId(),
                                                name: parseTextValue(cols[fieldName['Designator']]) + " (" + cols[fieldName['Layer']]+")",
                                                caption: comment,
                                                feeder: feederId,
                                                pos: {
                                                    x: tableX + parseFloatValue(cols[fieldName['Mid X']]),
                                                    y: tableY + parseFloatValue(cols[fieldName['Mid Y']]),
                                                    a: (parseFloatValue(cols[fieldName['Rotation']]) / 360.00)
                                                },
                                                active: true
                                            }
                                        )
                                    }
                                } else {
                                    n++
                                }

                            }
                        }
                    }
                    reader.onerror = (evt)=> {
                        console.log(evt)
                        alert("Can't read file '" + file.name + "'", "Error", 'error')
                    }

                    this.$refs.openFile.value = ''
                }

            },
            jogFirstElement() {
                if (this.project.elements.length > 0) {
                    this.$emit('goToElementCam', this.project.elements[0])
                } else {
                    alert('There is not a elements in the project', 'Warning', 'warning')
                }
            },
            setPCBPosCam() {
                if (this.machineStateIsOK() == true) {
                    this.project.pcb.pos.x = ((parseFloat(this.machinePos.x) - parseFloat(this.project.elements[0].pos.x)) + parseFloat(this.settings.cams[0].offset.x)).toFixed(3)
                    this.project.pcb.pos.y = ((parseFloat(this.machinePos.y) - parseFloat(this.project.elements[0].pos.y)) + parseFloat(this.settings.cams[0].offset.y)).toFixed(3)
                }
            },
            setPCBPos() {
                if (this.machineStateIsOK() == true) {
                    this.project.pcb.pos.x = (parseFloat(this.machinePos.x) - parseFloat(this.project.elements[0].pos.x)).toFixed(3)
                    this.project.pcb.pos.y = (parseFloat(this.machinePos.y) - parseFloat(this.project.elements[0].pos.y)).toFixed(3)
                }
            },
            adjPCBPositionCV() {
                this.$emit('adjPCBPositionCV', this.project)
            },
            findElement() {
                this.setCurrentElement(this.pnpProcessing.element)
                this.tab = 1
            },
            run() {
                this.$emit('run')
            },
            pause() {
                this.$emit('pause')
            },
            stop() {
                this.$emit('stop')
            }
        }
    }
</script>

<style>
.active-row {
    background-color: #F6F6F6 !important;
}
.project-name {
  padding: 0.5rem;
  margin-top: 0.5rem;
  margin-bottom: 0.5rem;
  border: 1px solid #e9ecef;
  border-left-width: 1px;
  border-left-color: rgb(233, 236, 239);
  border-left-width: .25rem;
  border-radius: .25rem;
  border-left-color: #f0ad4e !important;
}
</style>
