<template>
  <g class="flow-link" :class="{'flow-link--pointer':pointer}" :status="status" @click="$emit('click',$event)">
    <path class="flow-link__area" :d="path" />
    <path class="flow-link__visible" :d="path" />
    <path v-if="status" class="flow-link__status" :d="path" />
  </g>
</template>
<script>
const curve = 100
export default {
  name: 'FlowLink',
  props: {
    x1: {type: Number, default: 0},
    y1: {type: Number, default: 0},
    x2: {type: Number, default: 0},
    y2: {type: Number, default: 0},
    pointer: {type: Boolean, default: false},
    status: {type: String, default: null}
  },
  computed: {
    path () {
      const x1 = this.x1 + 7
      const y1 = this.y1
      const x2 = this.x2 - (this.pointer ? 4 : 15.5)
      const y2 = this.y2

      const dx = x2 - x1
      const dy = y2 - y1

      let s = curve
      let lineDist = 200
      let dist = Math.sqrt(dx * dx + dy * dy)

      // Reduce curve with distance
      if (dist < lineDist) {
        s = Math.max(curve - (lineDist - dist), 0)
      }
      s = Math.min(s, Math.min(dx, 100))

      let ox1 = s
      let oy1 = 0

      let ox2 = -s
      let oy2 = 0

      if (dx < 0) {
        ox1 = Math.min(-dx, 100)
        ox2 = -Math.min(-dx, 100)
        oy1 = Math.min(-dx, 150)
        oy2 = -Math.min(-dx, 150)
        if (dy < 0) {
          oy1 = -oy1
          oy2 = -oy2
        }
      }

      return `
      M${x1},${y1} 
      C${x1 + ox1},${y1 + oy1} 
      ${x2 + ox2},${y2 + oy2} 
      ${x2 - 1},${y2}
      L${x2} ${y2}
      `
    }
  }
}
</script>
<style>
.flow-view:not(.activity) .flow-link {
  cursor:pointer;
}

.flow-link__head{
  fill:#333;
}

.flow-link {
  stroke:#333;
}

.flow-link__area {
  stroke-width:20;
  stroke: transparent;
  fill: transparent;
}

.flow-link__visible{
  stroke-width:2;
  fill: transparent;
  marker-end:url(#head);
}

.flow-link--pointer {
  pointer-events:none;
}

.flow-link__status {
  opacity:1;
  stroke-width:4;
}

.flow-link[status=waiting] .flow-link__status {
  stroke-dasharray:8;
  stroke: grey;
  animation: dash 10s linear infinite;
}

.flow-link[status=running] .flow-link__status {
  stroke-dasharray:4,10;
  stroke: #aa2;
  animation: dash 1s linear infinite;
}

.flow-link[status=finish] .flow-link__status {
  stroke: green;
}

.flow-link[status=error] .flow-link__status {
  stroke: red;
}

@keyframes dash {
  from { stroke-dashoffset:100;}
  to { stroke-dashoffset: 0; }
}
</style>
