/*!\file: hydrology_core.cpp
 * \brief: core of the hydrology solution 
 */ 

#include "../toolkits/toolkits.h"
#include "../classes/objects/objects.h"
#include "../shared/shared.h"
#include "../io/io.h"
#include "../EnumDefinitions/EnumDefinitions.h"
#include "./solutions.h"
#include "../modules/modules.h"
#include "../solvers/solvers.h"

void hydrology_core(FemModel* femmodel){

	int i;

	/*intermediary*/
	IssmDouble time;
	int    nsteps;
	IssmDouble starttime,final_time;
	IssmDouble dt;
	bool   save_results;
	int    output_frequency;

	//first recover parameters common to all solutions
	femmodel->parameters->FindParam(&starttime,TimesteppingStartTimeEnum);
	femmodel->parameters->FindParam(&final_time,TimesteppingFinalTimeEnum);
	femmodel->parameters->FindParam(&dt,TimesteppingTimeStepEnum);
	femmodel->parameters->FindParam(&save_results,SaveResultsEnum);
	femmodel->parameters->FindParam(&output_frequency,SettingsOutputFrequencyEnum);
	/*first compute slopes: */
	surfaceslope_core(femmodel);
	bedslope_core(femmodel);

	/*Compute number of time steps: */
	if((dt==0)|| (final_time==0)){
		dt=0;
		nsteps=1;
	}
	else nsteps=reCast<int,IssmDouble>((final_time-starttime)/dt);
	time=starttime;

	/*Loop through time: */
	for(i=0;i<nsteps;i++){

		if(nsteps)if(VerboseSolution()) _pprintLine_("time step:" << i+1 << "/" << nsteps);
		time+=dt;
		femmodel->parameters->SetParam(time,TimeEnum);

		/*call hydrology_core step: */
		hydrology_core_step(femmodel,i,time);

		if(save_results && ((i+1)%output_frequency==0 || (i+1)==nsteps)){
			if(VerboseSolution()) _pprintLine_("   saving results ");
			//InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,WatercolumnEnum,i+1,time);
			//InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVxEnum,i+1,time);
			//InputToResultx(femmodel->elements,femmodel->nodes,femmodel->vertices,femmodel->loads,femmodel->materials,femmodel->parameters,HydrologyWaterVyEnum,i+1,time);

			/*unload results*/
			if(VerboseSolution()) _pprintLine_("   saving temporary results");
			OutputResultsx(femmodel->elements, femmodel->nodes, femmodel->vertices, femmodel->loads, femmodel->materials, femmodel->parameters,femmodel->results);
		}
	}
}
