import Base from './base';
import { getActualPoint, getClickPoint, createSvg, createElement } from './utils';
import { onClickOutside, toDateObject } from '../ui_utils'
import dayjs from 'dayjs'
import { TextStampColor } from '../../constants';

export default class Stamp extends Base {
  
  constructor ({
    container,
    annotation,
    messageHandler,
    page,
    viewport,
    scale,
    eventBus,
    layer,
    show = false
  }) {
    super({
      container,
      annotation,
      page,
      viewport,
      scale,
      eventBus,
      show
    })

    this.layer = layer
    this.hidden = true
    this.initial = false
    this.outline = null

    this.messageHandler = messageHandler

    this.start = null
    this.end = null

    this.newStart = null
    this.newEnd = 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.render()
  }

  async render () {
    if (!this.annotation.rect) {
      const getRect = await this.messageHandler.sendWithPromise('GetAnnotRect', {
        pagePtr: this.annotation.pagePtr,
        annotPtr: this.annotation.annotPtr
      })

      const pageWidth = this.viewport.viewBox[2]
      const pageHeight = this.viewport.viewBox[3]
      const imgWidth = getRect.right - getRect.left
      const imgHeight = getRect.bottom - getRect.top

      const left = (pageWidth - imgWidth) / 2
      const top = (pageHeight - imgHeight) / 2
      const right = (pageWidth + imgWidth) / 2
      const bottom = (pageHeight + imgHeight) / 2

      const rect = {
        left,
        top,
        right,
        bottom,
      }

      await this.messageHandler.sendWithPromise('SetAnnotRect', {
        pagePtr: this.annotation.pagePtr,
        annotPtr: this.annotation.annotPtr,
        rect
      })

      this.annotation.rect = rect
    }

    const annotation = this.annotation

    const { start, end } = this.getActualRect(
      this.viewport,
      this.scale
    )
    this.start = start
    this.end = end

    const rect = this.calculate(start, end)

    this.ratioRate = rect.height / rect.width

    const annotationContainer = document.createElement('div')
    annotationContainer.id = annotation.name
    annotationContainer.className = 'annotation'
    annotationContainer.style.top = rect.top + 'px'
    annotationContainer.style.left = rect.left + 'px'
    annotationContainer.style.width = rect.width + 'px'
    annotationContainer.style.height = rect.height + 'px'
    annotationContainer.style.fontSize = '0'

    let imgEle = null

    imgEle = document.createElement('img')
    imgEle.style.width = "100%"
    imgEle.style.height = "100%"

    let imgSrc = ''
    if (annotation.image) {
      imgSrc =  annotation.image
    }  else if (annotation.stampType === 'standard' || annotation.stampType === 'image' || annotation.stampType === 'text') {
      const imgRect = {
        width: parseInt(rect.width + 1),
        height: parseInt(rect.height + 1)
      }

      const imageArray = await this.messageHandler.sendWithPromise('GetRenderAnnot', {
        annotPtr: this.annotation.annotPtr,
        annotation: this.annotation,
        scale: this.scale
      })

      const canvas = document.createElement('canvas')
      canvas.style.width = imgRect.width + 'px'
      canvas.style.height = imgRect.height + 'px'
      canvas.width = imgRect.width
      canvas.height = imgRect.height
      let drawContext = canvas.getContext("2d")
      drawContext.clearRect(0, 0, canvas.width, canvas.height)
      let imageData = drawContext.createImageData(imgRect.width, imgRect.height)
      imageData.data.set(imageArray)
      drawContext.putImageData(imageData, 0, 0)
      imgSrc = canvas.toDataURL("image/png", 1)
    }

    imgEle.src = imgSrc
    this.imgEle = imgEle

    annotationContainer.append(this.imgEle)

    this.imgEle.addEventListener('mousedown', this.handleClick.bind(this))
    this.annotationContainer = annotationContainer

    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

    const left = (rect.left + rect.width - 30) + 'px'
    const top = (rect.top + rect.height + 8) + 'px'
    this.deletetButton.style.left = left
    this.deletetButton.style.top = top
    
    const outerLine = document.createElementNS("http://www.w3.org/2000/svg", "svg");

    outerLine.style.position = 'absolute'
    outerLine.style.zIndex = 1
    outerLine.style.left = `${rect.left - 7}px`
    outerLine.style.top = `${rect.top - 7}px`
    outerLine.style.width = `${rect.width + 7 * 2}px`
    outerLine.style.height = `${rect.height + 7 * 2}px`
    this.outerLine = outerLine

    this.moveRect = createSvg(
      "rect",
      {
        class: "move",
        'data-id': "move",
        stroke: "#1460F3",
        'stroke-width': 1,
        'fill-opacity': 0,
        width: rect.width + 8,
        height: rect.height + 8,
        x: 3,
        y: 3
      }
    );
    
    this.topLeftRect = createSvg(
      "rect",
      {
        class: "nw-resize",
        'data-id': "nw-resize",
        fill: "#1460F3",
        stroke: "none",
        width: 6,
        height: 6,
        x: 0,
        y: 0
      }
    );

    this.bottomLeftRect = createSvg(
      "rect",
      {
        class: "sw-resize",
        'data-id': "sw-resize",
        fill: "#1460F3",
        stroke: "none",
        width: 6,
        height: 6,
        x: 0,
        y: rect.height + 8
      }
    );
    
    this.bottomRightRect = createSvg(
      "rect",
      {
        class: "se-resize",
        'data-id': "se-resize",
        fill: "#1460F3",
        stroke: "none",
        width: 6,
        height: 6,
        x: rect.width + 8,
        y: rect.height + 8
      }
    );

    this.topRightRect = createSvg(
      "rect",
      {
        class: "ne-resize",
        'data-id': "ne-resize",
        fill: "#1460F3",
        stroke: "none",
        width: 6,
        height: 6,
        x: rect.width + 8,
        y: 0
      }
    );

    this.outerLine.append(this.moveRect)
    this.outerLine.append(this.topLeftRect)
    this.outerLine.append(this.bottomLeftRect)
    this.outerLine.append(this.bottomRightRect)
    this.outerLine.append(this.topRightRect)
    this.outerLineContainer.append(this.outerLine)
    this.outerLineContainer.append(this.deletetButton)
    this.initial = true

    this.eventBus.dispatch('imageChange')
    this.layer.annotationStore.creating = false
  }

  getActualRect (viewport, s,) {
    const annotation = this.annotation
    const { left: x1, top: y1, right: x2, bottom: y2 } = annotation.rect
    
    const start = getActualPoint(
      {
        x: x1,
        y: y1
      },
      viewport,
      s
    )
    const end = getActualPoint(
      {
        x: x2,
        y: y2
      },
      viewport,
      s
    )
    return {
      start,
      end
    }
  }

  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),
    };
  };

  calculate (start, end) {
    const initRect = this.rectCalc({ start, end })

    return {
      top: initRect.top,
      left: initRect.left,
      width: initRect.width,
      height: initRect.height,
    }
  }

  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

    const { width, height, rotation  } = this.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,
      },
    };
  }

  updateTool () {
    if (!this.initial) return
    if (this.hidden) {
      if (this.layer.selectedElementName === this.annotation.name) {
        this.layer.selectedElementName = null
      }
      this.outerLineContainer.remove()
    } else {
      if (this.layer.selectedElementName !== this.annotation.name) {
        this.layer.selectedElementName = this.annotation.name
      }
      this.container.append(this.outerLineContainer)
      this.outerLine.addEventListener('mousedown', this.onMousedown)
      this.outerLine.addEventListener('touchstart', this.onMousedown)
    }
  }

  handleClick (event) {
    if (this.layer.tool) {
      event.preventDefault()
    }
    if (!this.hidden || this.layer.annotationStore.creating) return
    this.hidden = false
    this.updateTool()
    onClickOutside([this.annotationContainer, this.outerLine, this.deletetButton], this.handleOutside.bind(this))
  }

  handleOutside () {
    this.hidden = !this.hidden
    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()
  }

  handleMouseDown (event) {
    if (event.button !== 0 && event.type === 'mousedown') return
    if (this.layer.tool) {
      event.stopPropagation()
    }
    if (event.type === 'touchstart') {
      document.body.style.overscrollBehavior = 'none';
      document.body.style.userSelect = 'none';
      document.getElementById('app').style.touchAction = 'none';
      document.querySelector('.document-container').style.overflow = 'hidden'
    }
    const operatorId = event.target.getAttribute('data-id')
  
    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 (this.layer.tool) {
      event.stopPropagation()
    }
    this.moving = true
    const { pageX, pageY } = getClickPoint(event)
    const start = this.start
    const end = this.end
    const startState = this.startState

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

      if (this.ratioRate) {
        let moveX = x1 - this.start.x
        let moveY = moveX * this.ratioRate
        y1 = this.start.y + moveY
        
        if (y1 < 0 || x1 < 0) return
      }

      this.update({
        start: { x: x1, y: y1 },
        end,
      });
     
    } else if (startState.operator === 'sw-resize') {
      let x1 = pageX - (startState.clickX - this.start.x);
      let y1 = pageY - (startState.clickY - this.end.y);
      x1 = Math.min(end.x - 5, x1)
      x1 = Math.max(0, x1)
      y1 = Math.min(height, y1)
      y1 = Math.max(start.y + 5, y1)

      if (this.ratioRate) {
        let moveX = x1 - this.start.x
        let moveY = moveX * this.ratioRate
        y1 = this.end.y - moveY
        if (y1 >= height || x1 < 0) return
      }

      this.update({
        start: { x: x1, y: start.y },
        end: { x: end.x, y: y1 },
      });
    } else if (startState.operator === 'se-resize') {
      let x = pageX - (startState.clickX - this.end.x);
      let y = pageY - (startState.clickY - this.end.y);
      x = Math.min(width, x)
      x = Math.max(start.x + 5, x)
      y = Math.min(height, y)
      y = Math.max(start.y + 5, y)

      if (this.ratioRate) {
        let moveX = this.end.x - x
        let moveY = moveX * this.ratioRate
        y = this.end.y - moveY

        if (y >= height || x >= width) return
      }

      this.update({
        start,
        end: { x, y },
      });
    } else if (startState.operator === 'ne-resize') {
      let x = pageX - (startState.clickX - this.end.x);
      let y = pageY - (startState.clickY - this.start.y);
      x = Math.min(width, x)
      x = Math.max(start.x + 5, x)
      y = Math.min(end.y - 5, y)
      y = Math.max(0, y)

      if (this.ratioRate) {
        let moveX = this.end.x - x
        let moveY = moveX * this.ratioRate
        y = this.start.y + moveY

        if (y <=0 || x >= width) return
      }

      this.update({
        start: { x: start.x, y },
        end: { x, y: end.y },
      });
    } else if (startState.operator === 'move') {
      let x1 = pageX - (startState.clickX - this.start.x);
      let y1 = pageY - (startState.clickY - this.start.y);
      let x2 = pageX - (startState.clickX - this.end.x);
      let y2 = pageY - (startState.clickY - this.end.y);

      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 },
      });
    }
  }

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

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

  handleMouseUp (event) {
    if (event.button !== 0 && event.type === 'mouseup') return
    if (this.layer.tool) {
      event.stopPropagation()
    }
    if (event.type === 'touchend') {
      document.body.style.overscrollBehavior = 'auto';
      document.body.style.userSelect = 'auto';
      document.getElementById('app').style.touchAction = 'auto';
      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)
    
    const { pageX, pageY } = getClickPoint(event)
    if (pageX === this.startState.clickX && pageY === this.startState.clickY) return

    this.start = this.newStart
    this.end = this.newEnd

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

    const rect = {
      left: start.x,
      top: start.y,
      right: end.x,
      bottom: end.y,
    }

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

  update ({ start, end }) {
    const rect = this.calculate(start, end)

    this.newStart = start
    this.newEnd = end

    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.imgEle.style.width = rect.width + 'px'
    this.imgEle.style.height = rect.height + 'px'

    this.outerLine.style.left = `${rect.left - 7}px`
    this.outerLine.style.top = `${rect.top - 7}px`
    this.outerLine.style.width = `${rect.width + 7 * 2}px`
    this.outerLine.style.height = `${rect.height + 7 * 2}px`

    const left = (rect.left + rect.width - 30) + 'px'
    const top = (rect.top + rect.height + 8) + 'px'
    this.deletetButton.style.left = left
    this.deletetButton.style.top = top
    
    this.moveRect.setAttribute('width',  rect.width + 8)
    this.moveRect.setAttribute('height',  rect.height + 8)
    
    this.bottomLeftRect.setAttribute("y", rect.height + 8)

    this.bottomRightRect.setAttribute("x", rect.width + 8)
    this.bottomRightRect.setAttribute("y", rect.height + 8)
    
    this.topRightRect.setAttribute("x", rect.width + 8)
  }
}
