import numpy
import os
from pairoptions import *
from MatlabFuncs import *

def checkfield(md,fieldname,*args):
	"""
	CHECKFIELD - check field consistency

	    Used to check model consistency.
	    Available options:
	       - NaN: 1 if check that there is no NaN
	       - size: [lines cols], NaN for non checked dimensions
	       - >:  greater than provided value
	       - >=: greater or equal to provided value
	       - <:  smallerthan provided value
	       - <=: smaller or equal to provided value
	       - < vec:  smallerthan provided values on each vertex
	       - forcing: 1 if check forcing consistency (size and time)
	       - values: cell of strings or vector of acceptable values
	       - numel: list of acceptable number of elements
	       - cell: 1 if check that is cell
	       - empty: 1 if check that non empty
	       - message: overloaded error message

	    Usage:
	       md = checkfield(md,fieldname,options);

	    Example:
	       md = checkfield(md,'mesh.elementonbed','size',[md.mesh.numberofelements 1],'values',[0 1]);
	       md = checkfield(md,'diagnostic.icefront','size',[NaN 4],'NaN',1);
	       md = checkfield(md,'diagnostic.icefront(:,end)','values',[0 1 2]);
	"""

	#get options
	options=pairoptions(*args)

	#get field from model
	field=getattr(md,fieldname)

	#check empty
	if 'empty' in options:
		if not field:
			md = md.checkmessage(options.getfieldvalue('message',\
				"field '%s' is empty" % fieldname))

	#Check size
	if 'size' in options:
		fieldsize=options.getfieldvalue('size')
		if   numpy.isnan(fieldsize[0]):
			if not numpy.size(field,1)==fieldsize[1]:
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' should have %d columns" % (fieldname,fieldsize[1])))
		elif numpy.isnan(fieldsize[1]):
			if not numpy.size(field,0)==fieldsize[0]:
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' should have %d lines" % (fieldname,fieldsize[0])))
		else:
			if (not numpy.size(field,0)==fieldsize[0]) or (not numpy.size(field,1)==fieldsize[1]):
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' size should be %d x %d" % (fieldname,fieldsize[0],fieldsize[1])))
	
	#Check numel
	if 'numel' in options:
		fieldnumel=options.getfieldvalue('numel')
		if not numpy.size(field) in fieldnumel:
			if   len(fieldnumel)==1:
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' size should be %d" % (fieldname,fieldnumel)))
			elif len(fieldnumel)==2:
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' size should be %d or %d" % (fieldname,fieldnumel[0],fieldnumel[1])))
			else:
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' size should be %s" % (fieldname,fieldnumel)))

	#check NaN
	if options.getfieldvalue('NaN',0):
		if True in numpy.isnan(field):
			md = md.checkmessage(options.getfieldvalue('message',\
				"NaN values found in field '%s'" % fieldname))

	#check cell
	if options.getfieldvalue('cell',0):
		if not isinstance(field,(tuple,list,dict)):
			md = md.checkmessage(options.getfieldvalue('message',\
				"field '%s' should be a cell" % fieldname))

	#check values
	if 'values' in options:
		fieldvalues=options.getfieldvalue('values')
		if False in ismember(field,fieldvalues):
			if   len(fieldvalues)==1:
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' value should be '%s'"  % (fieldname,fieldvalues[0])))
			elif len(fieldvalues)==2:
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' values should be '%s' or '%s'"  % (fieldname,fieldvalues[0],fieldvalues[1])))
			else:
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' should have values in %s" % (fieldname,fieldvalues)))

	#check greater
	if '>=' in options:
		lowerbound=options.getfieldvalue('>=')
		if numpy.any(field<lowerbound):
			md = md.checkmessage(options.getfieldvalue('message',\
				"field '%s' should have values above %d" % (fieldname,lowerbound)))
	if '>' in options:
		lowerbound=options.getfieldvalue('>')
		if numpy.any(field<=lowerbound):
			md = md.checkmessage(options.getfieldvalue('message',\
				"field '%s' should have values above %d" % (fieldname,lowerbound)))

	#check smaller
	if '<=' in options:
		upperbound=options.getfieldvalue('<=')
		if numpy.any(field>upperbound):
			md = md.checkmessage(options.getfieldvalue('message',\
				"field '%s' should have values below %d" % (fieldname,upperbound)))
	if '<' in options:
		upperbound=options.getfieldvalue('<')
		if numpy.any(field>=upperbound):
			md = md.checkmessage(options.getfieldvalue('message',\
				"field '%s' should have values below %d" % (fieldname,upperbound)))

	#check file
	if options.getfieldvalue('file',0):
		if not os.path.exists(field):
			md = md.checkmessage("file provided in '%s': '%s' does not exist" % (fieldname,field))

	#Check forcings (size and times)
	if options.getfieldvalue('forcing',0):
		if   numpy.size(field,0)==md.mesh.numberofvertices:
			if not numpy.size(field,1)==1:
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' should have only one column as there are md.mesh.numberofvertices lines" % fieldname))
		elif numpy.size(field,0)==md.mesh.numberofvertices+1:
			if not numpy.all(field[-1,:]==numpy.sort(field[-1,:])):
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' columns should be sorted chronologically" % fieldname))
			if nump.any(field[-1,0:-1]==field[-1,1:]):
				md = md.checkmessage(options.getfieldvalue('message',\
					"field '%s' columns must not contain duplicate timesteps" % fieldname))
		else:
			md = md.checkmessage(options.getfieldvalue('message',\
				"field '%s' should have md.mesh.numberofvertices or md.mesh.numberofvertices+1 lines" % fieldname))

	return md

