# -*- coding: utf-8 -*- 

import numpy as nmp
import matplotlib.pyplot as plt # for plotting
import matplotlib.ticker as mtick
import os

#Modules for handling time instances
import time as tm
import matplotlib.dates as dts
import datetime as dtm

import sys

font = {'family': 'serif',
	'weight': 'normal'}
plt.rc('font', **font)
plt.rc('text', usetex=True)
plt.rc('text.latex',unicode=True)
plt.rc('text.latex',preamble='\usepackage[utf8]{inputenc}')
plt.rc('text.latex',preamble='\usepackage[russian]{babel}')

#path = ['../results/windforc_base/hourly/', \
#        '../results/windforc_kor/hourly/', \
#        '../results/windforc_dynpgrad4/hourly/'] # path to files
path = ['../results/Mojai2016/hourly/']

#pathobs = os.path.expanduser('/home/victor/Files/main/observdata/Mojai2016/surveys_04-07-2016_temp.csv')
pathobs = os.path.expanduser('/home/victor/Files/main/observdata/Mojai2016/surveys_22-08-2016_temp.csv')

nonval = -999.

expnames = [''] #[u'K-P',u'K-P+kor',u'K-P+bts',u'K-P+bcs']
year = '2016'

npaths = len(path)

##Input from command line arguments
#nm0 = int(sys.argv[1])
#nd0 = int(sys.argv[2])
#ndlast = int(sys.argv[3])
#nh0 = int(sys.argv[4])
#nhlast = int(sys.argv[5])
#nhstep = int(sys.argv[6])

nm0 = int(input("Enter month \n"))
nd0 = int(input("Enter first day \n"))
ndlast = int(input("Enter last day \n"))
nh0 = int(input("Enter first hour \n"))
nhlast = int(input("Enter last hour \n"))
nhstep = int(input("Enter time step, hours \n"))

#nh0 = 0

# Time variables
timezone = None
time0_date = dtm.datetime(int(year),nm0,nd0,nh0,0,0,0,timezone)
time0_ = dts.date2num(time0_date)

fonts = 20 #font size

linestyles = ['-','--','-.',':']
linecolors = ['b','g','r','c','m','y','k']
ncolors = len(linecolors)

varname = []
basefilename = []
ncol = []
ncols = []
nheader = []
scale = []

#varname = 'Absolute value of velocity'
#ylabel  = 'Depth, m' #$\circ C$
#xlabel  = varname + ', $m/s$'
#basefilename = 'Profiles'
#ncol = 14 #The column number to display, 2 for temperature
#ncols = 14 #Total number of columns
#nheader = 14 #Number of lines in the header


varname.append(u'Температура (модель)')
ylabel  = u'Глубина, м' #$\circ C$
xlabel  = varname[len(varname)-1] + u',~К'
basefilename.append('Profiles')
ncol.append(2) #The column number to display, 2 for temperature
ncols.append(14) #Total number of columns
nheader.append(14) #Number of lines in the header
scale.append(1.)
#xmin = -8.E-2
#xmax = 8.E-2


#varname.append(u'Компонента скорости по оси $x$')
#ylabel  = u'Глубина, м' #$\circ C$
#xlabel  = varname[len(varname)-1] + u',~м/с'
#basefilename.append('Profiles')
#ncol.append(12) #The column number to display, 2 for temperature
#ncols.append(14) #Total number of columns
#nheader.append(14) #Number of lines in the header
#scale.append(1.)
#xmin = -8.E-2
#xmax = 8.E-2

#varname = u'Турбулентная кинетическая энергия'
#ylabel  = u'Глубина, м' #$\circ C$
#xlabel  = varname + u',~м$^2$/с$^2$'
#basefilename = 'Profiles'
#ncol = 5 #The column number to display, 2 for temperature
#ncols = 14 #Total number of columns
#nheader = 14 #Number of lines in the header

#varname = u'Скорость диссипации ТКЭ'
#ylabel  = u'Глубина, м' #$\circ C$
#xlabel  = varname + u',~м$^2$/с$^3$'
#basefilename = 'Profiles'
#ncol = 6 #The column number to display, 2 for temperature
#ncols = 14 #Total number of columns
#nheader = 14 #Number of lines in the header

#varname = u'Коэффициент вязкости для ТКЭ'
#ylabel  = u'Глубина, м' #$\circ C$
#xlabel  = varname + u',~м$^2$/с'
#basefilename = 'Profiles'
#ncol = 7 #The column number to display, 2 for temperature
#ncols = 14 #Total number of columns
#nheader = 14 #Number of lines in the header

#varname.append(u'Сдвиговая генерация')
#varname.append(u'S')
#ylabel  = u'Глубина, м' #$\circ C$
##xlabel  = varname[len(varname)-1] + u', м$^2$/с$^3$'
#basefilename.append('TKE_budget')
#ncol.append(2)
#ncols.append(6)
#nheader.append(7)
#scale.append(1.)

#varname.append(u'Источник/сток за счет плавучести')
#varname.append(u'B')
#ylabel  = u'Глубина, м' #$\circ C$
##xlabel  = varname[len(varname)-1] + u', м$^2$/с$^3$'
#basefilename.append('TKE_budget')
#ncol.append(4)
#ncols.append(6)
#nheader.append(7)
#scale.append(1.)

#varname.append(u'Диссипация ТКЭ')
#varname.append(u'$\epsilon$')
#ylabel  = u'Глубина, м' #$\circ C$
##xlabel  = varname[len(varname)-1] + u', м$^2$/с$^3$'
#basefilename.append('TKE_budget')
#ncol.append(5)
#ncols.append(6)
#nheader.append(7)
#scale.append(-1.)

#varname.append(u'Перенос ТКЭ')
#ylabel  = u'Глубина, м' #$\circ C$
##xlabel  = varname[len(varname)-1] + u', м$^2$/с$^3$'
#basefilename.append('TKE_budget')
#ncol.append(6)
#ncols.append(6)
#nheader.append(7)
#scale.append(1.)

xlabel = u'Температура, $^{\circ}C$' #u'Слагаемые уравнения баланса ТКЭ, м$^2$/с$^3$'

nvars = len(varname)

#fileout = 'uspeed'
#fileout = 'TKE_terms'
fileout = 'temp'

#Files names suffixes (timestamps)
nfiles = 0 #number of files
#time = [year + str(nm0).zfill(2) + str(nd0).zfill(2) + str(nh0).zfill(2)]
time = []
time_ = [dts.num2date(time0_)]
timew = time0_
nd = nd0
nh = nh0
nm = nm0
while not ((nd == ndlast and nh > nhlast) or (nd > ndlast)):
	time.append(year + str(nm).zfill(2) + str(nd).zfill(2) + str(nh).zfill(2))
	nfiles += 1
	#nh += nhstep # Incrementing by nhstep
	timew += nhstep/24. #timew is measured in days
	time_.append(dts.num2date(timew))
	nm = dts.num2date(timew).month
	nd = dts.num2date(timew).day
	nh = dts.num2date(timew).hour

#print(time_)

#Constructing legend
#nh = nh0
legendtime = []
#for np in range(npaths):
nd = dts.num2date(time0_).day
nh = dts.num2date(time0_).hour
timew = time0_
while not ((nd == ndlast and nh > nhlast) or (nd > ndlast)):
	legendtime.append(str(nd).zfill(2) + '.' + str(nm).zfill(2) + '.' + year + ' ' + \
		str(nh).zfill(2) + ':00')# + expnames[np])
	#nh += nhstep # Incrementing by nhstep
	timew += nhstep/24. #timew is measured in days
	#nm = dts.num2date(timew).month
	nd = dts.num2date(timew).day
	nh = dts.num2date(timew).hour

# Cycle over list of paths to data of the same structure
legenditems = []
for np in range(npaths):
	# Cycle over files in each path
	for k in range(nvars):	
		for i in range(nfiles):
			print (i)
			fid = open(path[np]+basefilename[k]+'  1  1'+str(time[i])+'.dat','r')
			#Reading the header
			for j in range(nheader[k]):
				line = fid.readline()
			if i == 0 :
				#Counting the number of raws in a file (assuming the same in all files)
				array = fid.read()
				nraws = array.count('\n')
				print('The number of levels is '+str(nraws))
				depths = [0]*nraws
				vals = [0]*nraws
				fid.seek(0) #rewinding file
				for j in range(nheader[k]):
					line = fid.readline()
			# Reading array of depths and values to be plotted
			for j in range(nraws) :
				line = fid.readline()
				line = line.split()
				depths[j] = abs(float(line[0]))
				vals[j] = float(line[ncol[k]-1])

			legenditems.append(varname[k]+ ', ' +legendtime[i]+expnames[np])
			for m in range(len(vals)) : vals[m] = vals[m]*scale[k]
			plt.plot(vals,depths,ls=linestyles[np],color=linecolors[k],linewidth=3)
	#print(depths)
	#print(vals)

#Reading and plotting observation files
# Input file:
# Time1 Time2 z1 (nvars values) z2 (nvars values) ...
nprec = 2 
nvars = 12
nvar = [1,2,3]
if 'pathobs' in locals():
	fobs = open(pathobs,'r')
	line = fobs.readline()
	line = line.split()
	print(line)
	nrecs = (len(line) - nprec)/(nvars + 1)
        nvarsd = len(nvar)
        legobs = [u'Среднее',u'Плотина',u'Красновидово']
	for i in range(nvarsd): legenditems.append(legobs[i])
	varobs = nmp.zeros((nrecs,nvarsd))
	z = nmp.zeros(nrecs)
	for i in range(nrecs):
		z[i] = float(line[2+i*(nvars+1)])
		for j in range(nvarsd):
			varobs[i,j] = float(line[2+i*(nvars+1)+nvar[j]])
			if (varobs[i,j] == nonval): varobs[i,j] = None
	print(z)
	for i in range(nvarsd): 
		plt.plot(varobs[:,i],z,ls='--', \
	        color=linecolors[i],linewidth=3)

plt.xlabel(xlabel,fontsize=fonts)
plt.ylabel(ylabel,fontsize=fonts)
plt.legend(legenditems,loc='best',fontsize=20)

plt.gca().tick_params(labelsize=20)
#tick.label.set_fontsize(14)
#plt.gca().xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e'))

plt.gca().invert_yaxis()

if 'xmin' in locals(): plt.gca().set_xlim([xmin, xmax])




plt.savefig(path[np] + fileout + '_' + year + str(nm).zfill(2) + str(ndlast).zfill(2) + str(nhlast).zfill(2) + '_hourly.png')
plt.show()



