package projetofinal;

import javax.swing.*;

public aspect ThreadSafeAspect {
	
	private Tela telaRef = null;
	private int replicacoes = 0;

	private Object lockReplicacoes = new Object();
	
	private int Simulator.ID = 0;
		
	public int Simulator.getID(){
		return(this.ID);
	}
	public Simulator.new(Tela nt, int nID){
		this(nt);
		this.ID=nID;
	}
	pointcut inicia() : execution(public void projetofinal.Simulator.iniciarSimulacao() );
        
	pointcut iniciaCall() : call(public void projetofinal.Simulator.iniciarSimulacao() );
	
	pointcut atribuihtml(HTMLw arq) : execution(public void projetofinal.Simulator.setOutHTML(HTMLw)) && args(arq) ;
        
	pointcut construtor(Tela tela) : initialization ( projetofinal.Simulator.new(Tela) )&& args(tela);
	
	pointcut execucao() : execution(public void projetofinal.Simulator.run(..));

	void around(HTMLw arq) : atribuihtml(arq){
		arq.fecha();
		arq = new HTMLw("saida"+((Simulator)thisJoinPoint.getThis()).getID()+".html");
		proceed(arq);
	}
	    
	after(Tela tela):construtor(tela){
		telaRef = tela;
	}

	before() : iniciaCall(){
		String ret = JOptionPane.showInputDialog(new JFrame(), "Quantas replicações :", "Deseja realizar mais simulações?", JOptionPane.QUESTION_MESSAGE);
		try{
			replicacoes = Integer.parseInt(ret);
		}catch(NumberFormatException _nfex){ 
			System.out.println(_nfex.getMessage());
			replicacoes=0;
		}
	}

	void around() : execucao(){
		synchronized(this.lockReplicacoes){
			proceed();
		}
	}


	after() : inicia(){
		for (int i = 0; i < replicacoes; i++) {
			
			Simulator sim = new Simulator(telaRef,i+1);
			//synchronized(this.lockReplicacoes){
			try {
		  		new Thread(sim,"Replicação "+(i+1)).start();
			}
			catch (Exception ex) {
				System.out.println(ex.getMessage());
			}
			//}
		}
	}
}
