import numpy as np
import os
from datetime import datetime

def imgName(tt=0):
	ut = datetime.utcnow()
	eye, emo, eda, eho, emi, ese = str(ut.year), str(ut.month), str(ut.day), str(ut.hour), str(ut.minute), str(ut.second)
	emse = str(ut.microsecond)
	if int(emo)<10: emo = "0%s"%emo
	if int(eda)<10: eda = "0%s"%eda
	if int(eho)<10: eho = "0%s"%eho
	if int(emi)<10: emi = "0%s"%emi
	if int(ese)<10: ese = "0%s"%ese

	if tt==0:
		namekey = "CSST%s%s%sT%s%s%s"%(eye,emo,eda,eho,emi,ese)
	elif tt==1:
		namekey = "%s-%s-%sT%s:%s:%s.%s"%(eye,emo,eda,eho,emi,ese,emse)
	elif tt==2:
		namekey = "%s%s%s%s%s%s"%(eye,emo,eda,eho,emi,ese)
	else:
		raise ValueError("!!! Give a right 'tt' value.")

	return namekey

def makeSubDir(path_dict, config):
	subImgdir = path_dict["output_img_dir"] + config["mockImgDir"] + '/'
	if not os.path.exists(subImgdir):
		os.system("mkdir %s"%subImgdir)
	imgKey0 = imgName(tt=0)
	imgKey1 = imgName(tt=1)
	imgKey2 = imgName(tt=2)
	subImgdir = subImgdir + imgKey0 + config["reIndex"] + config["reShear"] + "/"
	if not os.path.exists(subImgdir):
		os.system("mkdir %s"%subImgdir)
	return subImgdir, imgKey0, imgKey1, imgKey2

def makeSubDir_PointingList(path_dict, config, pointing_ID=0):
	imgDir = path_dict["work_dir"] + config["mockImgDir"] + '/'
	if not os.path.exists(imgDir):
		os.system("mkdir %s"%imgDir)
	# prefix = "MSC_" + config["date_obs"] + config["time_obs"] + "_" + str(pointing_ID).rjust(7, '0')
	prefix = "MSC_" + str(pointing_ID).rjust(7, '0')
	subImgdir = os.path.join(imgDir, prefix)
	if not os.path.exists(subImgdir):
		os.system("mkdir %s"%subImgdir)
	return subImgdir, prefix

def getShearFiled(config, shear_cat_file=None):
	if not config["shear_method"] in ["constant", "extra"]:
		raise ValueError("Please set a right 'shear_method' parameter.")

	if config["shear_method"] == "constant":
		g1 = config["reduced_g1"]
		g2 = config["reduced_g2"]
		reduced_shear = np.sqrt(g1**2 + g2**2)
		nshear = 1
		# TODO logging
	else:
		# TODO logging
		# if not os.path.exists(shear_cat_file):
		# 	raise ValueError("Cannot find shear catalog file.")
		# shearCat = np.loadtxt(shear_cat_file)
		# nshear = shearCat.shape[0]
		# g1, g2 = shearCat[:, 0], shearCat[:, 1]
		pass
	return g1, g2, nshear