
import sys
import os
import cantera as ct
import json
import time
import copy
import matplotlib.pyplot as plt

from PyQt4 import uic
from PyQt4.QtGui import * 
from PyQt4.QtCore import * 

from src.core.def_tools import keys_sorted

from src.gui.def_dialog import *
from src.gui.dialog_mech import dialog_mech


from src.gui.def_run import write_sk_inp


class dialog_sk4comb(base_dialog):


	def act_browse(self):

		self.w = self.w
		if bool(self.w.txt_dir.text()):
			init_path = self.w.txt_dir.text()
		else:
			init_path = self.parent.project['dir_public']

		dir_sk = str(QFileDialog.getExistingDirectory(self.w, '', init_path))
		if bool(dir_sk):
			cti = os.path.join(dir_sk,'mech','chem.cti')
			if os.path.exists(cti) == False:
				msg = 'no such file \n\n' + cti
				QMessageBox.information(QWidget(),'',msg)
			else:
				self.w.txt_dir.setText(dir_sk)
				ns_txt = os.path.join(dir_sk,'mech','ns.txt')
				if os.path.join(ns_txt):
					with open(ns_txt, 'r') as f:
						ns = f.read()
						self.w.label_ns.setText('n_species = '+ns)


	# init ============================

	def init_data_default(self):
		self.data = dict()
		self.data['folder'] = ''
		self.data['name'] = self.new_name('sk', self.occupied)


	def init(self):

		self.ui_name = 'sk4comb.ui'
		self.key = 'sk4comb'
		self.init_ui()
		self.occupied = self.init_occupied()
		self.init_data()

		# set connection ====================

		self.w.btn_save.clicked.connect(self.act_save)
		self.w.btn_dir.clicked.connect(self.act_browse)

		# set variables ==============================

		self.w_txts = dict()
		self.w_txts['obj'] = [self.w.txt_dir]
		self.w_txts['key'] = ['folder']
		self.w_txts['name'] = ['folder']	
		self.w_txts['vali'] = [self.is_any]
		self.w_txts['empty'] = [False]
		self.w_txts['len'] = [None]
		self.w_txts['split'] = [False]

		# set ui obj ==============================

		self.set_name()
		self.set_txt()

		dir_sk = str(self.w.txt_dir.text())
		if bool(dir_sk):
			ns_txt = os.path.join(dir_sk,'mech','ns.txt')
			if os.path.join(ns_txt):
				with open(ns_txt, 'r') as f:
					ns = f.read()
					self.w.label_ns.setText('n_species = '+ns)


		# exec ==============================

		self.readers = [self.read_name, self.read_txt]
		if self.w.exec_() == QDialog.Rejected:
			self.data = None












class dialog_comb_sk(common):

	""" >>>>>>>>>>>>>------------------------------------------------
	1. dialog_post
	     called by: window_main
                                                     
	"""

	# set ==============================

	
	def set_list(self):

		
		key = self.key

		obj = self.w.list_sk
		model = QStandardItemModel()

		if key not in self.parent.project.keys():
			self.parent.project[key] = dict()

		for item_name in sorted(self.parent.project[key].keys()):
			#item = self.parent.project[key][item_name]
			Qitem = QStandardItem(item_name)
			#Qitem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
			Qitem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable)
			Qitem.setData(QVariant(Qt.Unchecked), Qt.CheckStateRole)
			model.appendRow(Qitem)

		obj.setModel(model)
		self.parent.app.processEvents()


	# act ==============================

	def act_add(self):
		key = self.key
		data = dialog_sk4comb(parent=self.parent, data_name=None).data
		if data is not None:
			self.parent.project[key][data['name']] = data
			self.set_list()


	def act_del(self):
		key = self.key
		obj = self.w.list_sk
		data_name = self.read_item(obj)
		if data_name == None:
			return None

		msg = 'are you sure to delete "'+data_name+'""?\n\n'+\
			'(you can uncheck it if you only donnot want to use it right now)'
		Qanswer = QMessageBox.question(QWidget(),'',msg, \
				QMessageBox.Yes | QMessageBox.No, QMessageBox.No)

		if Qanswer == QMessageBox.Yes:
			del self.parent.project[key][data_name]
			self.set_list()


	def act_edit(self):
		key = self.key
		obj = self.w.list_sk
		data_name = self.read_item(obj)
		if data_name == None:
			return None

		data = dialog_sk4comb(parent=self.parent, data_name=data_name).data	
		if data is not None:
			del self.parent.project[key][data_name]
			self.parent.project[key][data['name']] = data
			self.set_list()



	def act_comb_sk(self):

		
		
		sk_list = []

		model = self.w.list_sk.model()

		for j in range(model.rowCount()):
			item = str(model.item(j).text())	
			if model.item(j).checkState():
				sk_list.append(item)

		if bool(sk_list) == False:
			msg = 'no sk is selected/provided'
			QMessageBox.information(QWidget(),'',msg)
			return False

		notes = ['! generated by global pathway selection (Gao et al,'+\
			' Combustion and flame, 167 (2016) 238-247','',
			'! a union set of the following skeletal mechanisms']

		species_kept = set()
		name = ''

		for sk in sorted(sk_list):
			name += ('['+sk+']')
			dir_sk = self.parent.project[self.key][sk]['folder'][0]
			cti = os.path.join(dir_sk,'mech','chem.cti')
			soln = ct.Solution(cti)
			ss = [s.name for s in soln.species()]
			species_kept |= set(ss)

			notes += ['! '+sk+', n_species = '+str(len(ss)), '!     '+dir_sk]

		notes += ['']
		dir_mech_sk = os.path.join(self.parent.project['dir_public'],'combined', name, 'mech')
		if os.path.exists(dir_mech_sk):
			msg = 'already exists:\n\n'+dir_mech_sk
			QMessageBox.information(QWidget(),'',msg)
			return False

		dir_mech_de = os.path.join(self.parent.project['dir_public'],'detailed','mech')
		write_sk_inp(species_kept, dir_mech_de, dir_mech_sk, notes)

		msg = 'saved in:\n\n'+dir_mech_sk
		QMessageBox.information(QWidget(),'',msg)




	# init ============================



	def __init__(self, parent):

		self.key = 'sk4comb'
		self.data = dict()
		self.occupied = []

		self.parent = parent
		if self.key not in self.parent.project.keys():
			self.parent.project[self.key] = dict()

		self.ui_name = 'combine_sk.ui'
		self.w = uic.loadUi(os.path.join(self.parent.dir_ui, self.ui_name))
		self.w.setFixedSize(self.w.width(), self.w.height())	

		# set connection ====================

		self.w.btn_add.clicked.connect(self.act_add)
		self.w.btn_del.clicked.connect(self.act_del)
		self.w.btn_edit.clicked.connect(self.act_edit)
		self.w.btn_comb.clicked.connect(self.act_comb_sk)
		self.w.list_sk.doubleClicked.connect(self.act_edit)


		# exec ==============================
		self.set_list()
		self.w.exec_()

