package com.example.test.dtram;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;

import org.springframework.stereotype.Component;

import com.example.test.websocket.WebSocketHandler;

import java.util.HashMap;
import java.util.Map;

import algorithms.TypeInference;
import models.dataConstraintModel.JsonTerm;
import models.dataFlowModel.DataTransferModel;
import parser.Parser;
import simulator.Simulator;
import simulator.interfaces.html.HtmlElement;
import simulator.interfaces.html.HtmlPresenter;

@Component
public class Dtram{
	
	File file;
	DataTransferModel model;
	Simulator simulator;
	
	private final WebSocketHandler ws;
	
	private Map<String, HtmlElement> elements;
	
	HtmlPresenter presenter;
	
	Dtram(WebSocketHandler ws){
		this.ws = ws;
		elements = new HashMap<>();
	}
	
//	public void initModel(String path) {
//		file = new File(path);
//		System.out.println(path);
//		try {
//			Parser parser = new Parser(new BufferedReader(new FileReader(file)));
//			model  = parser.doParse();
//		}catch(Exception e) {
//			e.printStackTrace();
//		}
//	}
	
	public void initModel(String modelText) {
		
		StringReader stringReader = new StringReader(modelText);
        BufferedReader bufferedReader = new BufferedReader(stringReader);
		try {
			Parser parser = new Parser(bufferedReader);
			model  = parser.doParse();
			TypeInference.infer(model);
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void initModel(InputStream stream) {
		try {
			Parser parser = new Parser(new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8)));
			model  = parser.doParse();
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void startSimulator(String sessionId) {
		simulator = new Simulator(model);
		simulator.init();
		presenter = new HtmlPresenter(simulator, ws, elements, sessionId);
	}
	
	public void onRestEvent(String id, String method, JsonTerm message) {
		elements.get(id).onRestEvent(method, message);
	}
	
	public DataTransferModel getModel() {
		return model;
	}

}
