import Quest from "./quest";

export default class TuneSignal extends Quest {

	private img: HTMLImageElement | null = null

	private glitches

	private target = [
		Math.random() * 400 + 100,
		Math.random() * 400 + 100
	]

	private pos = [350, 350]

	private distToTarget: number = 0.5

	private found = false

	private timeToCheck = 200

	private zoom = 0

	init() {
		this.img = new Image()
		this.img.src = 'img/omicron.png'

		this.glitches = new Array(10).fill(true).map(() => this.getGlich())
	}

	public draw(ctx: CanvasRenderingContext2D) {
		if (!this.img) return

		if (!this.found) {
			ctx.globalAlpha = Math.max(0.1, 1 - (this.distToTarget * 2))

			for (let i = 0; i < 10; i++) {
				ctx.drawImage(
					this.img,
					0, i * 31, 310, 31,
					50 + this.glitches[i].position, 50 + i * 50, 500, 50
				)
			}

			ctx.globalAlpha = 1

			ctx.strokeStyle = 'yellow'

			ctx.beginPath()

			ctx.moveTo(this.pos[0], 0)
			ctx.lineTo(this.pos[0], 600)

			ctx.moveTo(0, this.pos[1])
			ctx.lineTo(600, this.pos[1])

			ctx.stroke()

			// ctx.strokeText('' + this.distToTarget, 10, 10)

		} else {
			ctx.globalAlpha = Math.max(0, 1 - this.zoom)

			const offset = 150 * this.zoom

			ctx.drawImage(
				this.img,
				50 - offset, 50 - offset, 500 + offset * 2, 500 + offset * 2
			)

			ctx.globalAlpha = 1
		}
	}

	public update(dt) {
		if (!this.found) {
			this.glitches.forEach((_, i, arr) => {
				_.position += _.direction * _.speed * Math.min(dt, 20)

				if (_.back) {
					if (_.position * _.direction > 0) {
						arr[i] = this.getGlich()
					}
				} else {
					if ((_.position - _.dest) * _.direction > 0) {
						_.back = true
						_.direction = -_.direction
					}
				}
			})

			this.timeToCheck -= dt

			this.found = this.timeToCheck < 0 && this.distToTarget < 0.01
			if (this.found) {
				this.showMessage('Подключено')
			}
		} else {
			this.zoom += dt / 1000
		}
	}

	private getGlich() {
		const dist = 20 * this.distToTarget
		const dest = Math.random() * dist * 2 - dist

		return {
			dest,
			direction: dest > 0 ? 1 : -1,
			position: 0,
			back: false,
			speed: this.distToTarget * (Math.random() * 7 + 2)
		}
	}

	public getCursor(x, y) {
		this.distToTarget = Math.hypot(x - this.target[0], y - this.target[1]) / 1000
		this.pos = [x, y]

		this.timeToCheck = 200

		return 'default'
	}

	public get result() {
		return this.found && this.zoom > 2
	}
}
