import Base from './base';
import { onClickOutside } from '../ui_utils'
import { getClickPoint, createSvg, createElement } from './utils';
import { MARGIN_DISTANCE } from '../../constants'
import ArrowHelper from './arrow'

export default class Line extends Base {
  constructor ({
    container,
    annotation,
    page,
    viewport,
    eventBus,
    layer,
    show = false,
    enableReply = true
  }) {
    super({
      container,
      annotation,
      page,
      layer,
      viewport,
      eventBus,
      show
    })
    this.enableReply = enableReply

    this.hidden = true
    this.initial = false

    this.start = null
    this.end = null

    this.newStart = null
    this.newEnd = null

    this.svgElement = null

    this.startCircle = null
    this.endCircle = null

    this.show = show

    this.onMousedown = this.handleMouseDown.bind(this)
    this.onMouseup = this.handleMouseUp.bind(this)
    this.onMousemove = this.handleMouseMove.bind(this)
    this.onDelete = this.handleDelete.bind(this)
    this.onOpenReply = this.openReply.bind(this)
    this.onKeydown = this.handleKeydown.bind(this)
    this.render()
    
  }

  render () {
    const annotation = this.annotation
    const { start, end } = this.getActualPoint(
      this.viewport,
      this.scale
    )
    this.start = start
    this.end = end
    const actualbdwidth = (this.annotation.borderWidth || 2) * this.scale
    const innerRect = this.calculate(start, end)
    let arrowLength = Math.max(actualbdwidth * 3, 12 * this.scale)

    if (!annotation.borderColor) {
      annotation.borderColor = '#FF0000'
    }

    const rect = {
      left: innerRect.left - arrowLength,
      top: innerRect.top - arrowLength,
      width: innerRect.width + 2 * arrowLength,
      height: innerRect.height + 2 * arrowLength
    }
    if (!rect.width && !rect.height) return

    this.svgElement = document.createElementNS("http://www.w3.org/2000/svg", "svg");

    this.svgElement.setAttribute("viewBox", `${rect.left} ${rect.top} ${rect.width} ${rect.height}`)
    let line=document.createElementNS("http://www.w3.org/2000/svg",'line')

    line.setAttribute("x1", this.start.x)
    line.setAttribute("y1", this.start.y)
    line.setAttribute("x2", this.end.x)
    line.setAttribute("y2", this.end.y)
    line.setAttribute("stroke", annotation.borderColor)
    line.setAttribute("stroke-width", actualbdwidth)
    if (annotation.opacity) {
      line.setAttribute("stroke-opacity", annotation.opacity)
    }
    
    this.svgElement.append(line)

    if (this.annotation.head || this.annotation.tail) {
      let arrowBuild = new ArrowHelper(this.start, this.end)
      let arrowUi = []
      if (this.annotation.head && this.annotation.head === "OpenArrow") {
        let arrowHead=arrowBuild.getStartArrow(30, arrowLength, false)
        if(arrowHead)
        {
          arrowHead.setAttribute('head','')
          arrowUi.push(arrowHead)
        }
      }

      if (this.annotation.tail && this.annotation.tail === "OpenArrow") {
        let arrowTail=arrowBuild.getEndArrow(30, arrowLength, false)
        if(arrowTail)
        {
          arrowTail.setAttribute('tail','')
          arrowUi.push(arrowTail)
        }
      }
      arrowUi.forEach(element => {
        if (element) {
          element.setAttribute("stroke", annotation.borderColor)
          element.setAttribute("stroke-width", actualbdwidth)
          element.setAttribute("fill", "none")
          if(annotation.opacity) {
            element.setAttribute("stroke-opacity", annotation.opacity)
          }
          this.svgElement.append(element)
        }
      });
    }

    this.annotationContainer = document.createElement('div')
    this.annotationContainer.append(this.svgElement)
    this.annotationContainer.id = annotation.name
    this.annotationContainer.className = 'annotation'
    this.annotationContainer.style.top = rect.top + 'px'
    this.annotationContainer.style.left = rect.left + 'px'
    this.annotationContainer.style.width = rect.width + 'px'
    this.annotationContainer.style.height = rect.height + 'px'
    this.svgElement.addEventListener('mousedown', this.handleClick.bind(this))

    this.container.append(this.annotationContainer)

    this.outerLineContainer = document.createElement('div')
    this.outerLineContainer.className = 'outline-container'
    this.deletetButton = createSvg(
      "svg",
      {
        width: "30",
        height: "30",
        viewBox: "0 0 30 30",
        fill: "none",
        class: 'delete-button'
      },
      {
        width: '30px',
        height: '30px'
      }
    );
    this.deletetButton.addEventListener('click', this.onDelete)
    this.deletetButton.innerHTML = this.deleteSvgStr
    
    this.deletetButton.style.left = (rect.left + rect.width + MARGIN_DISTANCE - 30) + 'px'
    this.deletetButton.style.top = (rect.top - MARGIN_DISTANCE - 30) + 'px'

    this.replyButton = createElement(
      'div',
      {
        width: '30px',
        height: '30px',
        background: '#DDE9FF',
        borderRadius: '2px',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center'
      },
      {
        class: 'reply-button'
      }
    );
    this.replyButton.addEventListener('click', this.onOpenReply)
    this.replyButton.innerHTML = this.replySvgStr
    this.replyButton.style.left = (rect.left + rect.width + MARGIN_DISTANCE - 65) + 'px'
    this.replyButton.style.top = (rect.top - MARGIN_DISTANCE - 30) + 'px'
    
    const outerLine = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    
    outerLine.setAttribute("data-id", "move");
    outerLine.setAttribute("height", rect.height);
    outerLine.setAttribute("viewBox", `${rect.left} ${rect.top} ${rect.width + MARGIN_DISTANCE * 2} ${rect.height + MARGIN_DISTANCE * 2}`)
    outerLine.style.position = 'absolute'
    outerLine.style.zIndex = 1
    outerLine.style.left = `${rect.left - MARGIN_DISTANCE}px`
    outerLine.style.top = `${rect.top - MARGIN_DISTANCE}px`
    outerLine.style.width = `${rect.width + MARGIN_DISTANCE * 2}px`
    outerLine.style.height = `${rect.height + MARGIN_DISTANCE * 2}px`
    this.outerLine = outerLine
    
    this.startCircle = createSvg(
      "circle",
      {
        class: "start",
        'data-id': "start",
        fill: "#1460F3",
        cx: start.x + MARGIN_DISTANCE,
        cy: start.y + MARGIN_DISTANCE,
        r: 6
      }
    );
    this.endCircle = createSvg(
      "circle",
      {
        class: "end",
        'data-id': "end",
        fill: "#1460F3",
        cx: end.x + MARGIN_DISTANCE,
        cy: end.y + MARGIN_DISTANCE,
        r: 6
      }
    );
    this.moveLine = createSvg(
      "line",
      {
        class: 'move',
        'data-id': "move",
        x1: start.x + MARGIN_DISTANCE,
        y1: start.y + MARGIN_DISTANCE,
        x2: end.x + MARGIN_DISTANCE,
        y2: end.y + MARGIN_DISTANCE,
        fill: 'transparent',
        stroke: 'transparent',
        'stroke-width': 5
      }
    )
    this.outerLine.append(this.moveLine)
    this.outerLine.append(this.startCircle)
    this.outerLine.append(this.endCircle)
    this.outerLineContainer.append(this.outerLine)
    this.outerLineContainer.append(this.deletetButton)
    this.enableReply && this.outerLineContainer.append(this.replyButton)
    this.initial = true

    if (this.show) {
      !this.layer.addMode && this.selectAnnotation()
      this.show = false
    }
  }

  selectAnnotation () {
    if (this.layer.selectedElementName === this.annotation.name) return
    this.handleClick()
  }

  handleClick (event) {
    if (!this.hidden || this.layer.annotationStore.creating || ['redaction', 'remove'].includes(this.layer.tool) || document.querySelector('.compare-document-container').contains(event?.target)) return
    this.hidden = false
    this.updateTool()
    onClickOutside([this.svgElement, this.outerLine, this.deletetButton, this.replyButton, document.querySelector('.toggle-button')], this.handleOutside.bind(this))
  }

  handleOutside () {
    this.hidden = true
    if (this.layer.selectedElementName === this.annotation.name) {
      this.layer.selectedElementName = null
    }
    this.outerLine?.removeEventListener('mousedown', this.onMousedown)
    this.outerLine?.removeEventListener('touchstart', this.onMousedown)
    this.outerLineContainer?.remove()

    const documentViewer = this.layer.documentViewer
    const scrollElement = documentViewer.getScrollViewElement()
    scrollElement.style.touchAction = 'auto'
  }

  getActualPoint (
    viewport,
    s,
  ) {
    const annotation = this.annotation
    if (!annotation.linePoints && annotation.start && annotation.end) {
      annotation.linePoints = annotation.start + ',' + annotation.end
    }
    let [startX, startY, endX, endY] = annotation.linePoints

    const { width, height, rotation  } = viewport;
    let x1, y1, x2, y2;
    x1 = startX * s;
    y1 = startY * s;
    x2 = endX * s;
    y2 = endY * s;
    return {
      start: {
        x: x1,
        y: y1,
      },
      end: {
        x: x2,
        y: y2,
      },
    };
  };

  getInitialPoint () {
    const s = this.scale
    const startX = this.start.x
    const startY = this.start.y
    const endX = this.end.x
    const endY = this.end.y

    let x1, y1, x2, y2;
    x1 = startX / s;
    y1 = startY / s;
    x2 = endX / s;
    y2 = endY / s;
    return {
      start: {
        x: x1,
        y: y1,
      },
      end: {
        x: x2,
        y: y2,
      },
    };
  }

  calculate (start, end) {
    const initRect = this.rectCalc({ start, end });
    const actualbdwidth = (this.annotation.borderWidth || 2) * this.scale
    if (this.annotation.arrow) {
      return {
        top: initRect.top - 5 * 2,
        left: initRect.left - 5 * 2,
        width: initRect.width + 5 * 4,
        height: initRect.height + 5 * 4,
      }
    } else {
      return {
        top: initRect.top - actualbdwidth / 2,
        left: initRect.left - actualbdwidth / 2,
        width: initRect.width + actualbdwidth,
        height: initRect.height + actualbdwidth,
      }
    }
  }

  rectCalc ({ start, end }) {
    return {
      top: start.y < end.y ? start.y : end.y,
      left: start.x < end.x ? start.x : end.x,
      width: Math.abs(end.x - start.x),
      height: Math.abs(end.y - start.y),
    };
  };

  updateTool () {
    if (!this.initial) return
    if (this.hidden) {
      if (this.layer.selectedElementName === this.annotation.name) {
        this.layer.selectedElementName = null
      }
      this.outerLineContainer.remove()
      document.removeEventListener('keydown', this.onKeydown)
    } else {
      if (this.layer.selectedElementName !== this.annotation.name) {
        const annotation = this.annotation
        this.layer.selectedElementName = annotation.name

        const annotationData = {
          ...annotation
        }
        delete annotationData.annotPtr
        delete annotationData.pagePtr
        delete annotationData.operate
        delete annotationData.targetPage
        delete annotationData.arrow

        this.eventBus.dispatch('annotationSelected', annotationData)
      }
      this.container.append(this.outerLineContainer)
      this.outerLine.addEventListener('mousedown', this.onMousedown)
      this.outerLine.addEventListener('touchstart', this.onMousedown)
      document.addEventListener('keydown', this.onKeydown)

      const documentViewer = this.layer.documentViewer
      const scrollElement = documentViewer.getScrollViewElement()
      scrollElement.style.touchAction = 'none'
    }
  }

  handleMouseDown (event) {
    if (event.button !== 0 && event.type === 'mousedown') return
    if (this.layer.tool) {
      event.stopPropagation()
    }
    const operatorId = event.target.getAttribute('data-id')
  
    const documentViewer = this.layer.documentViewer
    const scrollElement = documentViewer.getScrollViewElement()
    this.scrollTop = scrollElement.scrollTop
    this.scrollLeft = scrollElement.scrollLeft

    const { pageX, pageY } = getClickPoint(event)
    this.startState = {
      operator: operatorId,
      clickX: pageX,
      clickY: pageY,
    }
    document.addEventListener('mousemove', this.onMousemove)
    document.addEventListener('mouseup', this.onMouseup)
    document.addEventListener('touchmove', this.onMousemove)
    document.addEventListener('touchend', this.onMouseup)
    
  };

  handleMouseMove (event) {
    if (event.button !== 0 && event.type === 'mousemove') return
    if (event.type === 'touchmove') {
      document.querySelector('.document-container').addEventListener('scroll', event => event.preventDefault())
    }
    this.moving = true
    let { pageX, pageY } = getClickPoint(event)

    const documentViewer = this.layer.documentViewer
    const scrollElement = documentViewer.getScrollViewElement()
    const scrollTop = scrollElement.scrollTop
    const scrollLeft = scrollElement.scrollLeft
    pageX = pageX + scrollLeft - this.scrollLeft
    pageY = pageY + scrollTop - this.scrollTop

    const start = this.start
    const end = this.end
    const startState = this.startState

    const { width, height } = this.viewport
    if (startState.operator === 'start') {
      let x1 = pageX - (startState.clickX - this.start.x);
      let y1 = pageY - (startState.clickY - this.start.y);
      x1 = Math.min(width, x1)
      x1 = Math.max(0, x1)
      y1 = Math.min(height, y1)
      y1 = Math.max(0, y1)

      this.update({
        start: { x: x1, y: y1 },
        end,
      });
    } else if (startState.operator === 'end') {
      let x2 = pageX - (startState.clickX - this.end.x);
      let y2 = pageY - (startState.clickY - this.end.y);
      x2 = Math.min(width, x2)
      x2 = Math.max(0, x2)
      y2 = Math.min(height, y2)
      y2 = Math.max(0, y2)
      this.update({
        start,
        end: { x: x2, y: y2 },
      });
    } else if (startState.operator === 'move') {
      let x1, y1, x2, y2
      const documentViewer = this.layer.documentViewer

      let windowCoordinates = this.getMouseLocation(event);
      const page = documentViewer.getSelectedPage(windowCoordinates, windowCoordinates)
      if (page.first && page.first !== (this.page + 1)) {
        const pagePoint = documentViewer.windowToPage(windowCoordinates, page.first, false)

        const annotationHeight = Math.abs(start.y - end.y)
        x1 = pageX - (startState.clickX - this.start.x)
        y1 = page.first > (this.page + 1) ? pagePoint.y : pagePoint.y - annotationHeight
        x2 = pageX - (startState.clickX - this.end.x)
        y2 = page.first > (this.page + 1) ? pagePoint.y + annotationHeight : pagePoint.y
        this.page = page.first - 1

        this.annotationContainer.remove()
        this.outerLineContainer.remove()
        const container = documentViewer.pdfViewer._pages[this.page].compdfAnnotationLayer.div
        container.append(this.annotationContainer)
        container.append(this.outerLineContainer)

        this.container = container
      } else {
        x1 = pageX - (startState.clickX - this.start.x);
        y1 = pageY - (startState.clickY - this.start.y);
        x2 = pageX - (startState.clickX - this.end.x);
        y2 = pageY - (startState.clickY - this.end.y);

        const windowPoint1 = documentViewer.pageToWindow({
          x: x1,
          y: y1
        }, this.page + 1, false)
        const windowPoint2 = documentViewer.pageToWindow({
          x: x2,
          y: y2
        }, this.page + 1, false)
        let x = 0, y = 0
        if (pageY > startState.clickY) {
          y = scrollElement.offsetHeight - (windowPoint2.y - scrollElement.scrollTop - scrollElement.offsetTop)
          y = y < 100 ? 5 : 0
        } else if (pageY < startState.clickY) {
          y = windowPoint1.y - scrollElement.scrollTop - scrollElement.offsetTop
          y = y < 100 ? -5 : 0
        }
        if (pageX > startState.clickX) {
          x = scrollElement.offsetWidth - (windowPoint2.x - scrollElement.scrollLeft - scrollElement.offsetLeft)
          x = x < 100 ? 5 : 0
        } else if (pageX < startState.clickX) {
          x = (windowPoint1.x - scrollElement.scrollLeft - scrollElement.offsetLeft)
          x = x < 100 ? -5 : 0
        }

        if (x || y) {
          scrollElement.scrollTop += y
          scrollElement.scrollLeft += x
        }

        const rect = {
          width: Math.abs(start.x -end.x),
          height: Math.abs(start.y -end.y)
        }
        if (x1 < x2) {
          x1 = Math.max(0, x1)
          x1 = Math.min(width - rect.width, x1)
          x2 = Math.max(rect.width, x2)
          x2 = Math.min(width, x2)
        } else {
          x2 = Math.max(0, x2)
          x2 = Math.min(width - rect.width, x2)
          x1 = Math.max(rect.width, x1)
          x1 = Math.min(width, x1)
        }

        if (y1 < y2) {
          y1 = Math.max(0, y1)
          y1 = Math.min(height - rect.height, y1)
          y2 = Math.max(rect.height, y2)
          y2 = Math.min(height, y2)
        } else {
          y2 = Math.max(0, y2)
          y2 = Math.min(height - rect.height, y2)
          y1 = Math.max(rect.height, y1)
          y1 = Math.min(height, y1)
        }
      }

      this.update({
        start: { x: x1, y: y1 },
        end: { x: x2, y: y2 },
      });
    }
    startState.clickX = pageX
    startState.clickY = pageY
  }

  handleDelete (event) {
    if (this.layer.tool && event) {
      event.stopPropagation()
    }

    this.delete()
    const annotationData = {
      type: 'delete',
      annotation: {
        operate: "del-annot",
        name: this.annotation.name,
        pageIndex: this.page
      }
    }
    this.annotation.annotPtr && (annotationData.annotation.annotPtr = this.annotation.annotPtr)

    this.eventBus.dispatch('annotationChange', annotationData)
  }

  delete () {
    this.handleOutside()
    this.annotationContainer?.remove()
    this.annotation.isDelete = true
    this.layer.deleteAnnotationInLayer({
      name: this.annotation.name
    })
  }

  handleKeydown (event) {
    // if (event.key === 'Delete' || event.key === 'Backspace') {
    //   this.handleDelete()
    // }
  }


  handleMouseUp (event) {
    if (event.button !== 0 && event.type === 'mouseup') return
    if (this.layer.tool) {
      event.stopPropagation()
    }
    if (event.type === 'touchend') {
      document.querySelector('.document-container').style.overflow = 'auto'
    }
    this.moving = false
    document.removeEventListener('mousemove', this.onMousemove)
    document.removeEventListener('mouseup', this.onMouseup)
    document.removeEventListener('touchmove', this.onMousemove)
    document.removeEventListener('touchend', this.onMouseup)
    this.scrollLeft = 0
    this.scrollTop = 0

    const annotation = this.annotation
    const { start, end } = this.getInitialPoint()

    const linePoints = [start.x, start.y, end.x, end.y]
    annotation.linePoints = linePoints
    const left = Math.min(start.x, end.x)
    const top = Math.min(start.y, end.y)
    const right = Math.max(start.x, end.x)
    const bottom = Math.max(start.y, end.y)
    const rect = {
      left: left - 6,
      top: top - 6,
      right: right + 6,
      bottom: bottom + 6
    }
    annotation.rect = rect

    if (annotation.pageIndex !== this.page) {
      const annotationData = {
        type: 'delete',
        annotation: {
          operate: "del-annot",
          name: annotation.name,
          pageIndex: annotation.pageIndex,
          annotPtr: annotation.annotPtr
        }
      }
      this.eventBus.dispatch('annotationChange', annotationData)

      const newAnnotationData = Object.assign({}, annotation)
      delete newAnnotationData.annotPtr
      delete newAnnotationData.pagePtr
      delete newAnnotationData.name
      newAnnotationData.operate = 'add-annot'
      newAnnotationData.pageIndex = this.page
      this.eventBus.dispatch('annotationChange', {
        type: 'add',
        show: true,
        annotation: newAnnotationData
      })

      this.annotationContainer.remove()
      this.outerLineContainer.remove()
    } else {
      this.eventBus.dispatch('annotationChange', {
        type: 'modify',
        annotation: {
          operate: "mod-annot",
          name: annotation.name,
          pageIndex: this.page,
          pagePtr: annotation.pagePtr,
          annotPtr: annotation.annotPtr,
          linePoints,
          rect
        }
      })
    }
  }

  update ({ start, end }) {
    const innerRect = this.calculate(start, end)
    const actualbdwidth = (this.annotation.borderWidth || 2) * this.scale
    let arrowLength=Math.max(actualbdwidth*3,12*this.scale)
    const rect={
      left:innerRect.left-arrowLength,
      top:innerRect.top-arrowLength,
      width:innerRect.width+arrowLength*2,
      height:innerRect.height+arrowLength*2
    }

    this.start = start
    this.end = end

    this.svgElement.setAttribute("width", rect.width);
    this.svgElement.setAttribute("height", rect.height);
    this.svgElement.setAttribute("viewBox", `${rect.left} ${rect.top} ${rect.width} ${rect.height}`)

    const line = this.svgElement.querySelector('line')
    line.setAttribute("x1", start.x)
    line.setAttribute("y1", start.y)
    line.setAttribute("x2", end.x)
    line.setAttribute("y2", end.y)

    this.annotationContainer.style.top = rect.top + 'px'
    this.annotationContainer.style.left = rect.left + 'px'
    this.annotationContainer.style.width = rect.width + 'px'
    this.annotationContainer.style.height = rect.height + 'px'

    this.outerLine.setAttribute("height", rect.height);
    this.outerLine.setAttribute("viewBox", `${rect.left} ${rect.top} ${rect.width + MARGIN_DISTANCE * 2} ${rect.height + MARGIN_DISTANCE * 2}`)
    this.outerLine.style.left = `${rect.left - MARGIN_DISTANCE}px`
    this.outerLine.style.top = `${rect.top - MARGIN_DISTANCE}px`
    this.outerLine.style.width = `${rect.width + MARGIN_DISTANCE * 2}px`
    this.outerLine.style.height = `${rect.height + MARGIN_DISTANCE * 2}px`

    this.deletetButton.style.left = (rect.left + rect.width + MARGIN_DISTANCE - 30) + 'px'
    this.deletetButton.style.top = (rect.top - MARGIN_DISTANCE - 30) + 'px'
    this.replyButton.style.left = (rect.left + rect.width + MARGIN_DISTANCE - 65) + 'px'
    this.replyButton.style.top = (rect.top - MARGIN_DISTANCE - 30) + 'px'
    
    this.startCircle.setAttribute("cx", start.x + MARGIN_DISTANCE)
    this.startCircle.setAttribute("cy", start.y + MARGIN_DISTANCE)
    this.endCircle.setAttribute("cx", end.x + MARGIN_DISTANCE)
    this.endCircle.setAttribute("cy", end.y + MARGIN_DISTANCE)
    
    this.moveLine.setAttribute("x1", start.x + MARGIN_DISTANCE)
    this.moveLine.setAttribute("y1", start.y + MARGIN_DISTANCE)
    this.moveLine.setAttribute("x2", end.x + MARGIN_DISTANCE)
    this.moveLine.setAttribute("y2", end.y + MARGIN_DISTANCE)

    if (this.annotation.head || this.annotation.tail) {
      let arrow = new ArrowHelper(start, end)
      if(this.annotation.head && this.annotation.head==='OpenArrow')
      {
        let head= this.svgElement.querySelector('[head]')
        if(head)
        {
          let arrowPoints= arrow.getStartArrowPoints(30, arrowLength)
          let points = ''
          arrowPoints.forEach(element => {
              if (points.length > 0) {
                  points = points + ' '
              }
              points = points + `${element.x},${element.y}`
          });
          if (points.length > 0) {
            head.setAttribute('points', points)
          }
        }
      }
      if(this.annotation.tail && this.annotation.tail === 'OpenArrow')
      {
        let tail= this.svgElement.querySelector('[tail]')
        if(tail)
        {
          let arrowPoints= arrow.getEndArrowPoints(30, arrowLength)
          let points = ''
          arrowPoints.forEach(element => {
              if (points.length > 0) {
                  points = points + ' '
              }
              points = points + `${element.x},${element.y}`
          });
          if (points.length > 0) {
            tail.setAttribute('points', points)
          }
        }
      }
    }
  }

  openReply () {
    this.eventBus.dispatch('openAnnotationReply', this.annotation)
  }
}
