import { alert, confirm } from '../js/dialogs.js'

export default {
  methods: {
    //--------------------------------------------------------
    // Level 1
    //--------------------------------------------------------
    async sendCommandUI(cmd) {
      this.consoleLogAppend('>>> ' + cmd)
      if (this.portIsOpened) {

        //if (cmd == '$H') {
        //  this.machineState.status = 'Homing'
        //}

        await this.sendCommand(cmd)
        this.consoleLogAppend(this.request)
        if (cmd[0] == 'M') {
          await this.sendCommand('$G')
        }

        if (cmd !== '?') {
          await this.sendCommand('?')
        }

        while ((this.machineState.status !== 'Idle') && ( this.machineState.status !== 'Alarm') ) {
          await new Promise(r => setTimeout(r, 100));
          await this.sendCommand('?')
        }
      }
    },

    async sendCommands(cmdArray, wailIdle=false) {
      if (this.pnpProcessing.stopFlag == true) {
        return
      }

      // reset flags
      this.gCodeProcess.stopFlag = false
      this.gCodeProcess.pauseFlag = false

      for (let cmd of cmdArray) {
        console.log(cmd)
        await this.sendCommand(cmd)
        if (cmd !== '?') {
          await this.sendCommand('?')
        }
        if (wailIdle) {
          while (this.machineState.status !== 'Idle') {
            await new Promise(r => setTimeout(r, 100));
            await this.sendCommand('?')
          }
        }
        while ((this.gCodeProcess.pauseFlag == true) || (this.pnpProcessing.pauseFlag == true)) {
          //Wait
          await new Promise(resolve => setTimeout(resolve, 200))
        }
        if ((this.gCodeProcess.stopFlag == true) || (this.pnpProcessing.stopFlag == true)) {
          break
        }
      }

      // reset flags
      this.gCodeProcess.stopFlag = false
      this.gCodeProcess.pauseFlag = false
    },

    async sendCommand(cmd) {
      if (this.portIsOpened) {
        if (cmd == '$H') {
          this.machineState.status = 'Homing'
        }
        
        let command = Uint8Array.from(Array.from(cmd + "\n").map(letter => letter.charCodeAt(0)));
        await this.portConnection.write(command)
        await this.readRequest()
      }
    },

    async readRequest() {
      let request = await this.portConnection.read()
      this.parseRequest(request)
    },

    parseRequest(request) {
      let decoder = new TextDecoder();
      let str = decoder.decode(request);
      this.request = str

      // Parse state get after command '?'
      // <Idle|MPos:30.000,10.000,0.000,0.000>
      let regexp = /<([a-z,A-Z]*)\|MPos:(.*)>/g
      let matchAll = str.matchAll(regexp)
      matchAll = Array.from(matchAll)
      if (matchAll.length == 1) {
        if (matchAll[0].length == 3) {
          this.machineState.status = matchAll[0][1]
          let pos = matchAll[0][2].split(',')
          this.machineState.pos.x = parseFloat(pos[0])
          this.machineState.pos.y = parseFloat(pos[1])
          this.machineState.pos.z = parseFloat(pos[2])
          this.machineState.pos.a = parseFloat(pos[3])
        }
      } else {
        // Parse information get after commands '$I' or '$G'
        let regexp = /\[([a-z,A-Z, ]*):(.*)]/g
        let matchAll = str.matchAll(regexp)
        matchAll = Array.from(matchAll)
        if (matchAll.length > 0) {
          for (let item of matchAll) {
            if (item.length == 3) {
              this.machineState.info[item[1]] = item[2]
            }
          }
        } else {
          // Parse settings get after command '$$' or '$[0..9]*' ($10, $23, ...)
          let regexp = /\$([0-9]*)=(.*)/g
          let matchAll = str.matchAll(regexp)
          matchAll = Array.from(matchAll)
          if (matchAll.length > 0) {
            for (let item of matchAll) {
              if (item.length == 3) {
                this.machineState.settings[item[1]] = parseFloat(item[2])
              }
            }            
          }
        }
      }
    },

    //--------------------------------------------------------
    // Level 2
    //--------------------------------------------------------
    
    async getCVData(number) {
      let url = 'http://localhost:5000/cv/'+number+'?'+Date.now()
        let postdata = this.cvParams[number]
      return await this.fetch_execute_async( url, { method: 'POST', credentials: 'same-origin', cache: 'no-cache', headers: {'Content-Type': 'application/json;charset=utf-8'}, body: JSON.stringify(postdata)} )
    },

    fetch_execute_async: async function (url, options) {
      this.loading = true
      try {
        let response = await fetch(url, options)
        let result = await response.json()
        return result
      }
      catch (error) {
        console.log(error)
      }
      finally {
        this.loading = false
      }
    },

    async pnpGoToZero() {
      let commands = []
      let safePosZ = parseFloat(this.settings.heads[0].safePosZ)
      commands.push(`G0 Z${safePosZ}`)
      commands.push(`G0 X0 Y0`)
      commands.push(`G0 Z0`)
      await this.sendCommands(commands, true)
    },


    async pnpGoToParking() {
      let commands = []
      commands.push(`G0 Z${this.settings.parking.pos.z}`)
      commands.push(`G0 X${this.settings.parking.pos.x} Y${this.settings.parking.pos.y} A0`)
      await this.sendCommands(commands, true)
    },

    async pnpPumpOn() {
      let commands = []
      commands.push(this.settings.pump.On)
      commands.push(`$G`)
      await this.sendCommands(commands, true)
    },

    async pnpPumpOff() {
      let commands = []
      commands.push(this.settings.pump.Off)
      commands.push(`$G`)
      await this.sendCommands(commands, true)
    },

    async pnpValveOn(head) {
      let commands = []
      commands.push(`G04 P${head.pauseBeforeOn}`)
      commands.push(head.valveOn)
      commands.push(`G04 P${head.pauseAfterOn}`)
      commands.push(`$G`)
      await this.sendCommands(commands, true)
    },

    async pnpValveOff(head) {
      let commands = []
      commands.push(`G04 P${head.pauseBeforeOff}`)
      commands.push(head.valveOff)
      commands.push(`G04 P${head.pauseAfterOff}`)
      commands.push(`$G`)
      await this.sendCommands(commands, true)
    },

    async pnpLightOn(camN) {
      let commands = []
      commands.push(this.settings.cams[camN].lightOn)
      commands.push(`$G`)
      await this.sendCommands(commands, true)
    },

    async pnpLightOff(camN) {
      let commands = []
      commands.push(this.settings.cams[camN].lightOff)
      commands.push(`$G`)
      await this.sendCommands(commands, true)
    },

    // this.pnpSafetyUp()    - just Up to Safety Z
    // this.pnpSafetyUp(0)   - Up to Safety Z and Rotate to A=0
    async pnpSafetyUp(a) {
      let safePosZ = parseFloat(this.settings.heads[0].safePosZ)
      let cmd = `G0 Z${safePosZ}`
      if (!isNaN(a)) {
        cmd = cmd + ` A${a}`
      }
      let commands = [cmd]
      await this.sendCommands(commands, true)
    },

    // this.pnpSafetyGoToXYZ(x=10, y=10, z=10)
    // this.pnpSafetyGoToXYZ(10, 0, 10)
    // this.pnpSafetyGoToXYZ(x=10, y=10, z=NaN)  - finally Z = safePosZ
    // this.pnpSafetyGoToXYZ(10, 0, z=NaN)       - finally Z = safePosZ
    async pnpSafetyGoToXYZ(x, y, z) {
      let commands = []
      let safePosZ = parseFloat(this.settings.heads[0].safePosZ)
      commands.push(`G0 Z${safePosZ}`)
      commands.push(`G0 X${x} Y${y}`)
      if (!isNaN(z)) {
        commands.push(`G0 Z${z}`)
      }
      await this.sendCommands(commands, true)
    },

    // this.pnpGoToXYZA(x=NaN, y=NaN, z=-25, a=0)
    // this.pnpGoToXYZA(10, 20, NaN, NaN)
    // this.pnpGoToXYZA(NaN, NaN, 20, 0)
    async pnpGoToXYZA(x, y, z, a) {
      let cmd = 'G0'
      if (!isNaN(x)) cmd = cmd + ` X${x}`
      if (!isNaN(y)) cmd = cmd + ` Y${y}`
      if (!isNaN(z)) cmd = cmd + ` Z${z}`
      if (!isNaN(a)) cmd = cmd + ` A${a}`
      let commands = [cmd]
      await this.sendCommands(commands, true)
    },

    async pnpGoToXYZF(x, y, z, feed) {
      let cmd = 'G1'
      if (!isNaN(x)) cmd = cmd + ` X${x}`
      if (!isNaN(y)) cmd = cmd + ` Y${y}`
      if (!isNaN(z)) cmd = cmd + ` Z${z}`
      if (!isNaN(feed)) cmd = cmd + ` F${feed}`
      let commands = [cmd]
      await this.sendCommands(commands, true)
    },

    //--------------------------------------------------------
    // Level 3
    //--------------------------------------------------------

    //@pnpDo
    async pnpGoToBottomCam() {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true

        let bottomCamID = 1
        let x, y, z
        x = parseFloat(this.settings.cams[bottomCamID].pos.x)
        y = parseFloat(this.settings.cams[bottomCamID].pos.y)
        z = parseFloat(this.settings.cams[bottomCamID].pos.z)

        // Move to Bottom Cam X,Y
        await this.pnpSafetyGoToXYZ(x, y, NaN, NaN)

        // Light On
        await this.pnpLightOn(bottomCamID)

        // Move to Bottom Cam Z
        await this.pnpGoToXYZA(NaN, NaN, z, NaN)
      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    },

    // ---------------------------------
    // Go to feeder on safety Z position
    // ---------------------------------
    getFeederPos(feeder) {
        let x = 0
        let y = 0

        // Type Liner
        if (feeder.type == 0) {
          x = feeder.pos.x
          y = feeder.pos.y
        }

        // Type Push-Pull
        if (feeder.type == 1) {
          for (let point of feeder.pathPoints) {
            if (point.pick == true) {
              x = point.x
              y = point.y
            }
          }
        }

        return {x:x, y:y}
    },

    async pnpGoToFeeder(feeder) {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true
/*
        let x = 0
        let y = 0

        // Type Liner
        if (feeder.type == 0) {
          x = feeder.pos.x
          y = feeder.pos.y
        }

        // Type Push-Pull
        if (feeder.type == 1) {
          for (let point of feeder.pathPoints) {
            if (point.pick == true) {
              x = point.x
              y = point.y
            }
          }
        }
*/
        let pos = this.getFeederPos(feeder)
        await this.pnpSafetyGoToXYZ(pos.x, pos.y, NaN)

      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    },

    async pnpGoToFeederCam(feeder) {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true

        let pos = this.getFeederPos(feeder)

        pos.x = parseFloat(pos.x) - parseFloat(this.settings.cams[0].offset.x)
        pos.y = parseFloat(pos.y) - parseFloat(this.settings.cams[0].offset.y)

        await this.pnpSafetyGoToXYZ(pos.x, pos.y, NaN)

      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    },
    // ---------------------------------
    // Pick element rom feeder
    // ---------------------------------
    async pnpPickFromFeeder(feeder, headN=0) {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true

        let x, y, z
        let head = this.settings.heads[headN]

        // Type Liner
        if (feeder.type == 0) {
          if (parseInt(feeder.current)+1 < parseInt(feeder.capacity)) {

            if (this.valvesState[headN] == false) {
              x = parseFloat(feeder.pos.x) + parseFloat(feeder.step.x) * parseFloat(feeder.current)
              y = parseFloat(feeder.pos.y) + parseFloat(feeder.step.y) * parseFloat(feeder.current)
              z = parseFloat(feeder.pos.z) + parseFloat(feeder.step.z) * parseFloat(feeder.current)

              await this.pnpSafetyUp(0)
              await this.pnpSafetyGoToXYZ(x, y, z)
              await this.pnpValveOn(head)
              await this.pnpSafetyUp()

              feeder.current = parseInt(feeder.current)+1
            } else {
              await alert('Valve is On!', 'Warning', 'warning')
              return false
            }
          } else {
            await alert('Feeder is empty', 'Warning', 'warning')
            return false
          }
        }

        // Type Push-Pull
        if (feeder.type == 1) {
          await this.pnpSafetyUp(0)

          for (let point of feeder.pathPoints) {
            await this.pnpGoToXYZA(point.x, point.y, NaN, NaN)
            await this.pnpGoToXYZA(NaN, NaN, point.z, NaN)
            if (point.pick == true) {
              await this.pnpValveOn(head)
            }
          }
          await this.pnpSafetyUp()
        }

        return true
      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    },

    // ---------------------------------
    // To Basket
    // ---------------------------------
    async pnpDropIntoBasket() {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true

        let x = this.settings.basket.pos.x
        let y = this.settings.basket.pos.y
        let z = this.settings.basket.pos.z

        await this.pnpSafetyGoToXYZ(x, y, z)

        for (let head of this.settings.heads) {
          await this.pnpValveOff(head)
        }
        await this.pnpSafetyUp(0)
      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    },

    // ---------------------------------
    // Correct position
    // ---------------------------------
    async pnpFixPosition() {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true

        let bottomCamID = 1
        let x, y, z, a
        let cvData

        x = parseFloat(this.settings.cams[bottomCamID].pos.x)
        y = parseFloat(this.settings.cams[bottomCamID].pos.y)
        z = parseFloat(this.settings.cams[bottomCamID].pos.z)
        a = this.machinePos.a
        let aDegrees = a * 360.0

        await this.pnpGoToBottomCam()

        // Fix position and rotation in 3 iterations
        for (let i=0; i<3; i++) {
          // Pause before make Photo :)
          await new Promise(r => setTimeout(r, this.settings.cv[bottomCamID].pauseBefore*1000))
          // Get CV data
          cvData = await this.getCVData(bottomCamID)
          // If object is found
          if (typeof cvData.objects.object !== 'undefined') {
            // Fix Position X,Y
            let dx = Math.round(cvData.objects.object.dx*1000.0 / this.settings.cams[bottomCamID].ppmm) / 1000.0
            let dy = Math.round(cvData.objects.object.dy*1000.0 / this.settings.cams[bottomCamID].ppmm) / 1000.0
            x = x - dx
            y = y - dy

            // Fix Rotation
            let da = cvData.objects.object.angle_degrees

            // Align to vertical or horizontal
            if (da < -45.0) {
              da = 90.0 + da
            }
            if (da > 45.0) {
              da = -90.0 + da
            }
            // Recalculate to turn
            da = da / 360
            // Calculate absolute a
            a = a - da

            if ( (Math.abs(dx) < 5.0) && (Math.abs(dy) < 5.0) && (Math.abs(da) < 0.25) )  { // if dx, dy, da is in adequate range
              // Move and rotate
              await this.pnpGoToXYZA(x, y, NaN, a)
            }
          }
        }
        //

        // Light off
        await this.pnpLightOff(bottomCamID)

        let el_x = parseFloat(this.machinePos.x) - parseFloat(this.settings.cams[bottomCamID].pos.x)
        let el_y = parseFloat(this.machinePos.y) - parseFloat(this.settings.cams[bottomCamID].pos.y)
        let element_offsets = {x: el_x, y: el_y}
        return element_offsets
      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }


    },

    //--------------------------------------------------------
    async pnpGoToElement(element) {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true

        /*
        let x = element.pos.x
        let y = element.pos.y
        */

        let offsetPCB = this.project.pcb.pos

        let x = parseFloat(element.pos.x) + parseFloat(offsetPCB.x)
        let y = parseFloat(element.pos.y) + parseFloat(offsetPCB.y)

        await this.pnpSafetyGoToXYZ(x, y, NaN)
      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    },

    async pnpGoToElementCam(element) {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true

        /*
        let x = element.pos.x - this.settings.cams[0].offset.x
        let y = element.pos.y - this.settings.cams[0].offset.y
        */

        let offsetPCB = this.project.pcb.pos

        let x = parseFloat(element.pos.x) + parseFloat(offsetPCB.x) - parseFloat(this.settings.cams[0].offset.x)
        let y = parseFloat(element.pos.y) + parseFloat(offsetPCB.y) - parseFloat(this.settings.cams[0].offset.y)

        await this.pnpSafetyGoToXYZ(x, y, NaN)
      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    },
    //--------------------------------------------------------

    getNozzle(id) {
      for (let nozzle of this.settings.nozzles) {
        if (nozzle.id == id) {
          return nozzle
        }
      }
    },

    getNozzleOffset(nozzle, a) {
      if (a < 0) {
        a = 1.0 + a
      }
      for (let row of nozzle.calibrationData) {
        if (row.a >= a) {
          return row
        }
      }
    },


    async pnpPlaceElement(element) {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true

        let head = this.settings.heads[0]
        let PCBTableZ = parseFloat(this.settings.table.pos.z)

        let feederId = element.feeder
        let offsetPos = {x:0, y:0}
        let a = parseFloat(element.pos.a)

        for (let feeder of this.project.feeders) {
          if (feeder.id == feederId) {

            if (await this.pnpPickFromFeeder(feeder) == false) {
              return false
            }
            
            // Rotate element if need
            if (a !== 0.0) {
              await this.pnpGoToXYZA(NaN, NaN, NaN, a) 
            }

            // Correct Position
            if (feeder.posCorrection == true) {
              offsetPos = await this.pnpFixPosition() // Fix position
            } else {
              // Get nuzzle offsets here
              let nozzle = this.getNozzle(feeder.nozzle)
              let nozzleOffset = this.getNozzleOffset(nozzle, a)
              offsetPos.x = nozzleOffset.dx
              offsetPos.y = nozzleOffset.dy
            }

            let offsetPCB = this.project.pcb.pos
    
            let x = parseFloat(element.pos.x) + parseFloat(offsetPos.x) + parseFloat(offsetPCB.x)
            let y = parseFloat(element.pos.y) + parseFloat(offsetPos.y) + parseFloat(offsetPCB.y)
            let z = PCBTableZ + parseFloat(offsetPCB.z) + parseFloat(feeder.elementHeight)

            await this.pnpSafetyGoToXYZ(x, y, z)
            await this.pnpValveOff(head)
            await this.pnpSafetyUp()
            await this.pnpGoToXYZA(NaN, NaN, NaN, 0) 

          }
        }
        return true
      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    },
    //--------------------------------------------------------

    async pnpAutocalibrateNozzle(nozzle) {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {
        this.pnpProcessing.runFlag = true

        let bottomCamID = 1
        let ppmm = this.settings.cams[bottomCamID].ppmm

        await this.pnpSafetyUp(0)
        await this.pnpGoToBottomCam()

        for (let row of nozzle.calibrationData) {
          //if (row.a != 0) {
            await this.pnpGoToXYZA(NaN, NaN, NaN, row.a)
            // Pause before make Photo :)
            await new Promise(r => setTimeout(r, this.settings.cv[bottomCamID].pauseBefore*1000))
            let cvData = await this.getCVData(bottomCamID)
            if (typeof cvData.objects.nozzle != 'undefined') {
              row.dx = -(cvData.objects.nozzle.dx / ppmm).toFixed(3)
              row.dy = -(cvData.objects.nozzle.dy / ppmm).toFixed(3)
            } else {
              await alert("Autocalibration is failed! Nozzle not found!", 'Error', 'error')
              return
            }

          //}
        }
        
        // Light off
        await this.pnpLightOff(bottomCamID)
        await this.pnpSafetyUp(0)

        await alert("Calibration has been completed", 'Completed', 'success')
      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    },

    getNozzlePlace(nozzleId) {
      for (let place of this.settings.nozzlesHolder.places) {
        if (place.nozzleId == nozzleId) {
          return place
        }
      }
      return null
    },


    async pnpPullOffNozzle(nozzlePlace) {
      // Return true if head without Nozzle
      if (this.settings.heads[0].nozzle == -1) {
        return true
      }

      // Find empty place
      let emptyPlace = null
      for (let place of this.settings.nozzlesHolder.places) {
        if (place.nozzleId == -1) {
          emptyPlace = place
          break
        }
      }

      if (emptyPlace == null) {
        alert('Not found the empty place!', 'Error', 'error')
        return false
      }

      // Pull off the Nozzle
      console.log(emptyPlace)
      for (let i = emptyPlace.points.length-1; i >= 0; i--) {
        let point = emptyPlace.points[i]
        console.log(point)
        if (i == emptyPlace.points.length-1) {
          await this.pnpSafetyGoToXYZ(point.x, point.y, point.z)
        } else {
          await this.pnpGoToXYZF(point.x, point.y, point.z, nozzlePlace.feed)
        }
      }

      // Set current Nozzle to empty place
      emptyPlace.nozzleId = this.settings.heads[0].nozzle
      // Set head empty
      this.settings.heads[0].nozzle = -1

      return true
    },

    async pnpPutOnNozzle(nozzlePlace) {
      if (nozzlePlace.nozzleId == -1) {
        alert('Specified Nozzle place is empty!', 'Error', 'error')
        return
      }
      if (nozzlePlace.points.length == 0) {
        alert('Not specified the path to take!', 'Error', 'error')
        return
      }
      
/*
      // Find empty place
      let emptyPlace = null
      for (let place of this.settings.nozzlesHolder.places) {
        if (place.nozzleId == -1) {
          emptyPlace = place
          break
        }
      }

      if (emptyPlace == null) {
        alert('Not found the empty place!', 'Error', 'error')
        return
      }

      // Pull off the Nozzle
      console.log(emptyPlace)
      for (let i = emptyPlace.points.length-1; i >= 0; i--) {
        let point = emptyPlace.points[i]
        console.log(point)
        if (i == emptyPlace.points.length-1) {
          await this.pnpSafetyGoToXYZ(point.x, point.y, point.z)
        } else {
          await this.pnpGoToXYZF(point.x, point.y, point.z, nozzlePlace.feed)
        }
      }

      // Set current Nozzle to empty place
      emptyPlace.nozzleId = this.settings.heads[0].nozzle
*/
      if (await this.pnpPullOffNozzle(nozzlePlace) == false) {
          return
      }



      // Put on the Nozzle
      console.log(nozzlePlace)
      for (let i = 0; i < nozzlePlace.points.length; i++) {
        let point = nozzlePlace.points[i]
        console.log(point)
        if (i == 0) {
          await this.pnpSafetyGoToXYZ(point.x, point.y, point.z)
        } else {
          await this.pnpGoToXYZF(point.x, point.y, point.z, nozzlePlace.feed)
        }
      }

      // Set The current Nozzle
      this.settings.heads[0].nozzle = nozzlePlace.nozzleId

      // Set The empty place
      nozzlePlace.nozzleId = -1

      await this.pnpSafetyUp(0)
    },

    //--------------------------------------------------------
    async pnpJobStart(startElement = null) {
      // Prepare elements list      
      let elements = []

      if (startElement !== null) {
        elements = this.project.elements.slice(this.project.elements.indexOf(startElement), this.project.elements.length)
      } else {
        elements = this.project.elements
      }

      // Check required Nozzles in holder
      for (let element of elements) {
        if (element.active == true) {
          if (element.nozzleId != this.settings.heads[0].nozzle) {
            let nozzlePlace = this.getNozzlePlace(element.nozzleId)
            if (nozzlePlace == null) {
              let nozzle = this.getNozzle(element.nozzleId)
              alert (`Can't start Job because the nozzles holder doesn't have the required nozzle '${nozzle.name}'`, 'Warning', 'warning')
              return
            }
          }
        }
      }

      // Checking current Nozzle and empty place
      let nozzle = this.getNozzle(this.settings.heads[0].nozzle)
      let emptyPlace = this.getNozzlePlace(-1)
      await confirm(`Head is use the Nozzle '${nozzle.name}'. Empty place in the Nozzles Holder is '${emptyPlace.name}'. Is it correct? Shall we begin?`, 'Please check').then(async (res)=> {
          if (res == true) {
            // Start Job procesing
            this.pnpJobProcessing(elements)
          }
      })
    },
    //--------------------------------------------------------

    async pnpJobProcessing(elements) {
      let pnpProcessing = this.pnpProcessing.runFlag
      try {

        this.pnpProcessing.runFlag = true
        this.pnpProcessingRun()

        await this.pnpPumpOn()

        // Remember Current Nozzle
        let RememberNozzleId = this.settings.heads[0].nozzle

        for (let element of elements) {
          if (this.pnpProcessing.stopFlag == false) {

            if (element.active == true) {
              this.pnpProcessing.element = element
              this.pnpProcessing.message = `Element is being placed: ${element.name}`

              // Check Nozzle
              if (element.nozzleId != this.settings.heads[0].nozzle) {
                let nozzlePlace = this.getNozzlePlace(element.nozzleId)
                console.log('Change Nozzle')
                console.log(nozzlePlace)
                // Change Nozzle
                await this.pnpPutOnNozzle(nozzlePlace)
              }

              if (await this.pnpPlaceElement(element) == false) {
                await alert("Job is braked!", 'Warning', 'warning')
                return false
              }
            }

          }
        }

        // Restore Nozle
        if (this.settings.heads[0].nozzle != RememberNozzleId) {
          let nozzlePlace = this.getNozzlePlace(RememberNozzleId)
          await this.pnpPutOnNozzle(nozzlePlace)
        }

        await this.pnpPumpOff()
        await this.pnpGoToParking()

        if (this.pnpProcessing.stopFlag == true) {
          this.pnpProcessing.message = `The Job has been canceled on Element: ${this.pnpProcessing.element.name}`

          await alert("The Job has been canceled!", 'Canceled', 'warning')
          this.pnpProcessingReset()
        } else {
          this.pnpProcessing.message = 'Completed'
          this.pnpProcessing.element = null
          await alert("The project \"" +  this.project.name + "\" has been completed", 'Completed', 'success')
          this.pnpProcessing.message = ''
        }

        //return true
      } finally {
        this.pnpProcessing.runFlag = pnpProcessing
      }
    }

  }
}
