import {Circle} from "./circle.js"
import {Api} from './api.js'
import config from '../config.json'

export class Manager {

	constructor() {

		this.circles = {};
		this.api = new Api();
		this.eventSource = new EventSource(config.endpoint+"/sse");
		this.r = Math.min(windowWidth, windowHeight) / 10;
		this.init();
	}

	init() {

		this.api.fetch('POST', '/api/init', {})
			.then((response) => {
				let data = response.data;
				for (let uuid of Object.keys(data)) {
					let param = data[uuid];
					let x = (param.x * windowWidth) / 100
					let y = (param.y * windowHeight) / 100
					let r = this.r;
					this.circles[uuid] = new Circle(x, y, r, param.color,param)
				}
			})

		this.eventSource.addEventListener('add', (e) => {
			let data = JSON.parse(e.data);
			let x = (data.x * windowWidth) / 100
			let y = (data.y * windowHeight) / 100
			let r = Math.min(windowWidth, windowHeight) / 10;
			let circle = new Circle(x, y, r, data.color);
			this.circles[data.uuid] = circle;
		})

		this.eventSource.addEventListener('delete', (e) => {
			let data = JSON.parse(e.data);
			delete this.circles[data.uuid];
		})
	}

	draw() {

		for(let uuid of Object.keys(this.circles)) {
			let circle = this.circles[uuid];
			circle.draw();
		}
	}

	onRisize() {
		let newCircles = {}
		this.r = Math.min(windowWidth, windowHeight) / 10;
		for(let uuid of Object.keys(this.circles)) {
			let circle = this.circles[uuid];
			let x = (circle.data.x * windowWidth) / 100
			let y = (circle.data.y * windowHeight) / 100
			let r = this.r;
			newCircles[uuid] = new Circle(x, y, r, circle.data.color, circle.data)
		}
		this.circles = newCircles;
	}

	onClose() {
		this.eventSource.close();
		this.api.fetch('DELETE', '/sse', {})
	}

	onClick() {

		let create = true;

		for(let uuid of Object.keys(this.circles)) {
			let circle = this.circles[uuid];
			let d = dist(mouseX, mouseY, circle.x, circle.y);
		  if (d < this.r && circle.status) {

				circle.status = false;

				this.api.fetch('POST', '/api/delete', {
					uuid : uuid
				}).then((data) => {
					setTimeout(() => {
						circle.status = true;
					}, 200)

				})
				create = false;

		  }
		}

		if (create) {

			let circle = new Circle(mouseX, mouseY);

			this.api.fetch('POST', '/api/add', {
				x : (100*circle.x)/windowWidth,
				y : (100*circle.y)/windowHeight,
				color : circle.color.levels
			})
		}

	}
}
