import numpy
from fielddisplay import fielddisplay
from EnumDefinitions import *
from StringToEnum import StringToEnum
from checkfield import *
from WriteData import *
from MatlabFuncs import *

class groundingline(object):
	"""
	GROUNDINGLINE class definition

	   Usage:
	      groundingline=groundingline();
	"""

	def __init__(self): # {{{
		self.migration=''
		self.melting_rate=float('NaN')

		#set defaults
		self.setdefaultparameters()

		#}}}
	def __repr__(self): # {{{
		string='   grounding line migration parameters:'

		string="%s\n%s"%(string,fielddisplay(self,'migration','type of grounding line migration: ''SoftMigration'',''AgressiveMigration'' or ''None'''))
		string="%s\n%s"%(string,fielddisplay(self,'melting_rate','melting rate applied when previously grounded parts start floating [m/yr]'))
		return string
		#}}}	
	def setdefaultparameters(self): # {{{

		#Type of migration
		self.migration='None'

		#basal melting rate correction: 
		self.melting_rate=0;

		return self
	#}}}
	def checkconsistency(self,md,solution,analyses):    # {{{

		md = checkfield(md,'groundingline.migration','values',['None','AgressiveMigration','SoftMigration','SubelementMigration','SubelementMigration2'])

		if not strcmp(self.migration,'None'):
			if numpy.any(numpy.isnan(md.geometry.bathymetry)):
				md.checkmessage("requesting grounding line migration, but bathymetry is absent!")
			pos=numpy.nonzero(md.mask.groundedice_levelset>0.)[0]
			if any(numpy.abs(md.geometry.bed[pos]-md.geometry.bathymetry[pos])>10**-10):
				md.checkmessage("bathymetry not equal to bed on grounded ice!")
			pos=numpy.nonzero(md.mask.groundedice_levelset<0.)[0]
			if any(md.geometry.bathymetry[pos]-md.geometry.bed[pos]>10**-9):
				md.checkmessage("bathymetry superior to bed on floating ice!")

		return md
	# }}}
	def marshall(self,md,fid):    # {{{
		WriteData(fid,'data',StringToEnum(self.migration)[0],'enum',GroundinglineMigrationEnum(),'format','Integer')
		WriteData(fid,'object',self,'fieldname','melting_rate','format','Double')
	# }}}
