# Copyright (c) 2010 Anil Kumar
# All rights reserved.
#
# License: BSD 

import os
import sys
import re

from PyQt6 import QtWidgets, QtGui, QtCore, uic

from PyQt6.QtWidgets import *
from PyQt6.QtGui import *
from PyQt6.QtCore import *

def show_msg_dialog(msg):
	QMessageBox.warning(None, "Seascope", msg, QMessageBox.StandardButton.Ok)

def dir_scan_csope_files(rootdir):
	file_list = []
	if (not os.path.isdir(rootdir)):
		print("Not a directory:", rootdir)
		return file_list
	for root, subFolders, files in os.walk(rootdir):
		for f in files:
			f = os.path.join(root, f)
			if (re.search(r'\.(h|c|H|C|hh|cc|hpp|cpp|hxx|cxx||l|y|s|S|pl|pm|java)$', f) != None):
				file_list.append(f)
	return file_list

class CscopeProjectSettingsDialog(QDialog):
	def __init__(self):
		QDialog.__init__(self)

		self.ui = uic.loadUi('ui/cscope_prj_settings.ui', self)
		self.pd_path_tbtn.setIcon(QFileIconProvider().icon(QFileIconProvider.IconType.Folder))

		self.pd_src_list.setSelectionMode(QAbstractItemView.SelectionMode.ExtendedSelection)

		self.pd_path_tbtn.clicked.connect(self.path_open_cb)
		self.pd_add_btn.clicked.connect(self.src_add_cb)
		self.pd_rem_btn.clicked.connect(self.src_rem_cb)
		self.accepted.connect(self.ok_btn_cb)

	def path_open_cb(self):
		fdlg = QFileDialog(None, "Choose directory")
		fdlg.setFileMode(QFileDialog.FileMode.Directory);
		fdlg.setDirectory(self.pd_path_inp.text())
		if (fdlg.exec()):
			path_dir = fdlg.selectedFiles()[0];
			self.pd_path_inp.setText(str(path_dir))

	def src_add_cb(self):
		fdlg = QFileDialog(None, "Choose directory")
		fdlg.setFileMode(QFileDialog.FileMode.Directory);
		fdlg.setDirectory(self.pd_path_inp.text())
		if (fdlg.exec()):
			d = fdlg.selectedFiles()[0];
			d = str(d)
			d = d.strip()
			if (d == None):
				return
			d = os.path.normpath(d)
			if (d == '' or not os.path.isabs(d)):
				return
			self.src_add_files(d)

	def src_rem_cb(self):
		li = self.pd_src_list
		for item in li.selectedItems():
			row = li.row(item)
			li.takeItem(row)

	def src_add_files(self, src_dir):
		file_list = dir_scan_csope_files(src_dir)
		self.pd_src_list.addItems(file_list)

	def ok_btn_cb(self):
		proj_dir = os.path.join(str(self.pd_path_inp.text()), str(self.pd_name_inp.text()))
		proj_dir = os.path.normpath(proj_dir)
		if (self.is_new_proj):
			if (proj_dir == '' or not os.path.isabs(proj_dir)):
				return
			if (os.path.exists(proj_dir)):
				show_msg_dialog("\nProject already exists")
				return
			os.mkdir(proj_dir)
		# File list
		cs_list = []
		for inx in range(self.pd_src_list.count()):
			val = str(self.pd_src_list.item(inx).text())
			cs_list.append(val)
		cs_list = list(set(cs_list))
		# Cscope opt
		cs_opt = []
		if self.pd_invert_chkbox.isChecked():
			cs_opt.append('-q')
		if self.pd_kernel_chkbox.isChecked():
			cs_opt.append('-k')

		self.res = [proj_dir, cs_opt, cs_list]

	def set_proj_args(self, proj_args):
		(proj_dir, cs_opt, cs_list) = proj_args
		(proj_base, proj_name) = os.path.split(proj_dir)
		self.pd_path_inp.setText(proj_base)
		self.pd_name_inp.setText(proj_name)
		# File list
		fl = cs_list
		self.pd_src_list.addItems(fl)
		# Cscope opt
		for opt in cs_opt:
			if (opt == '-q'):
				self.pd_invert_chkbox.setChecked(True)
			if (opt == '-k'):
				self.pd_kernel_chkbox.setChecked(True)

	def run_dialog(self, prj_type, proj_args):
		assert prj_type == 'cscope'
		self.pd_src_list.clear()
		if (proj_args == None):
			self.is_new_proj = True
			self.pd_invert_chkbox.setChecked(True)
		else:
			self.is_new_proj = False
			self.set_proj_args(proj_args)
		self.res = None
		
		self.pd_path_frame.setEnabled(self.is_new_proj)

		while True:
			ret = self.exec()
			if (ret == QDialog.DialogCode.Accepted or ret == QDialog.DialogCode.Rejected):
				break
		return self.res
