import { rules, isCanRepeat } from './connectionRule.js'

function findConnection(instance, sourceId, targetId) {
  let connections = instance.getAllConnections()

  return connections.find(val => val.sourceId === 'legend' + sourceId && val.targetId === 'legend' + targetId)
}

function clearActiveConnection(operationItem, instance) {
  if (operationItem.type === 'connection') {
    const { sourceId, targetId } = operationItem

    const connection = findConnection(instance, sourceId, targetId)

    if (connection) {
      connection.removeClass('active-line')
    }
  }
}

function deleteConnection({ sourceId, targetId }, instance) {
  const connection = findConnection(instance, sourceId, targetId)

  if (connection) {
    instance.deleteConnection(connection)
  }
}

function setConnectionLabel(instance, sourceId, targetId, label) {
  let connection = findConnection(instance, sourceId, targetId)

  connection.getOverlay('label').setLabel(label)
}

function validateRepeatConnection(sourceNode, targetNode) {
  const line = sourceNode.lines.find(val => val.target === targetNode.id)

  return !line
}

function validateConnection(sourceNode, targetNode) {
  let isValidated = true
  let message = '不能重复连线'

  if (!isCanRepeat) {
    isValidated = validateRepeatConnection(sourceNode, targetNode)
  }

  if (!isValidated) {
    return {
      isValidated,
      message
    }
  }

  for (let n = 0; n < rules.length; n++) {
    if (sourceNode.type === rules[n].sourceType && targetNode.type === rules[n].targetType) {
      isValidated = false
      message = rules[n].message

      break
    }
  }

  return {
    isValidated,
    message
  }
}

export { findConnection, clearActiveConnection, deleteConnection, setConnectionLabel, validateConnection }
