#include <stdlib.h>
#include<math.h>

#include "general.h"
#include "vertex.h"
#include "cell.h"
#include "vesicle.h"
#include "frame.h"
char plugin_name[] = "Constant area";
char plugin_description[]= "Plugin that enables constant area of the vesicle.";
char plugin_author[] = "SAMO PENIC";


typedef struct {
	ts_double darea;
	ts_double A0;
	ts_double epsarea;
} plugin_data;


ts_plugin_details *init (){
	ts_plugin_details *details=(ts_plugin_details *)calloc(1,sizeof(ts_plugin_details));
	details->name = plugin_name;
	details->data = (plugin_data *)calloc(1,sizeof(plugin_data)); //storing data
	return details;	
}


ts_vesicle *after_vesicle_init(ts_vesicle *vesicle){
	plugin_data *data=(plugin_data *)vesicle->plist->pointer->plugin->details->data;
	ts_fprintf(stdout,"area volume initialized\n");
	centermass(vesicle);
	cell_occupation(vesicle);
	vesicle_area(vesicle);
	data->A0=vesicle->area;
	data->epsarea=data->A0/(ts_double)vesicle->tlist->n;
	return vesicle;
}


void vm_energy_before_prepare(ts_vesicle *vesicle, ts_vertex *vtx){	
    if(vesicle->tape->constareaswitch>0){
		plugin_data *data=(plugin_data *)vesicle->plist->pointer->plugin->details->data;
		data->darea=0;
		ts_uint i;
		for(i=0;i<vtx->tristar_no;i++) data->darea-=vtx->tristar[i]->area;
    
    }
}

ts_double vm_before_montecarlo_constraint(ts_vesicle *vesicle, ts_vertex *vtx, ts_vertex *old_vtx){
	if(vesicle->tape->constareaswitch>0){
		plugin_data *data=(plugin_data *)vesicle->plist->pointer->plugin->details->data;
		ts_uint i;
		for(i=0;i<vtx->tristar_no;i++) data->darea+=vtx->tristar[i]->area;
	        if(fabs(vesicle->area+data->darea-data->A0)>data->epsarea) return TS_FAIL;
    }
	return TS_SUCCESS;
}


void vm_new_state_accepted(ts_vesicle *vesicle, ts_vertex *vtx, ts_vertex *old_vtx){
	if(vesicle->tape->constareaswitch >0){
		plugin_data *data=(plugin_data *)vesicle->plist->pointer->plugin->details->data;
		vesicle->area+=data->darea;
	}
}