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

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,'fieldname','groundingline.migration','values',['None','AgressiveMigration','SoftMigration','SubelementMigration','SubelementMigration2'])

		if not m.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!")
			if any(md.geometry.bathymetry - md.geometry.bed > 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')
	# }}}
