package com.example.test.services;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;

import com.example.test.dtram.Dtram;
import com.example.test.websocket.IMessageReceiveListener;
import com.example.test.websocket.WebSocketHandler;

import models.algebra.Constant;
import models.dataConstraintModel.JsonTerm;
import parser.Parser;
import parser.Parser.TokenStream;
import parser.exceptions.ExpectedColon;
import parser.exceptions.ExpectedDoubleQuotation;
import parser.exceptions.ExpectedRightBracket;
import parser.exceptions.WrongJsonExpression;

@Service
public class ElementEventService implements IMessageReceiveListener{
	
	private final Dtram dtram;
	private final WebSocketHandler ws;
	private TokenStream stream;
	private Parser parser;
	
	ElementEventService(Dtram dtram, WebSocketHandler ws) {
		this.dtram = dtram;
		this.ws = ws;
		this.ws.addMessageListener(this);
		stream = new Parser.TokenStream();
		parser = new Parser(stream);
	}
	
	public JsonTerm handleMessage(String message){
		stream.addLine(message);
		System.out.println(message);
		try {
			return (JsonTerm) parser.parseTerm(stream, dtram.getModel());
		} catch (ExpectedRightBracket | WrongJsonExpression | ExpectedColon | ExpectedDoubleQuotation e) {
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	public void onReceivedMessage(String message, WebSocketSession session) {
		JsonTerm data = handleMessage(message);
		String method = (String)((Constant) data.get("method")).getValue();
		String id = (String)((Constant) data.get("id")).getValue();
		if(method.equals("connect")) {
			ws.connectIdToSession(id, session);
		} else if(method.equals("mouseEvent")) {
			String state = (String)((Constant) data.get("state")).getValue();
			switch(state) {
			case "1": onButtonPressed(id);break;
			case "0": onButtonReleased(id);break;
			}
		} else if(method.equals("textEvent")) {
			String newText = (String)((Constant) data.get("newText")).getValue();
			onTextChanged(id, newText);
		}
	}
	
	public void onButtonPressed(String id) {
		dtram.onRestEvent(id, "onMousePressed", null);
	}
	
	public void onButtonReleased(String id) {
		dtram.onRestEvent(id, "onMouseReleased", null);
	}
	
	public void onTextChanged(String id, String newText) {
		JsonTerm json = new JsonTerm();
		json.addMember("newText", new Constant(newText));
		dtram.onRestEvent(id, "onTextChanged", json);
	}
}
