#include "ubl-settings-usergroups.h"

ubl_settings_usergroups_group_creation_window *yon_ubl_settings_usergroups_group_creation_new(){
	ubl_settings_usergroups_group_creation_window *window = malloc(sizeof(ubl_settings_usergroups_group_creation_window));
	GtkBuilder *builder = gtk_builder_new_from_resource(glade_path_ubl_settings_usergroups_group_creation);
	window->CreateGroupWindow=yon_gtk_builder_get_widget(builder,"CreateGroupWindow");
	window->StatusBox=yon_gtk_builder_get_widget(builder,"StatusBox");
	window->userUIDAutoCheck=yon_gtk_builder_get_widget(builder,"GIDAutoCheck");
	window->userUIDEntry=yon_gtk_builder_get_widget(builder,"userUIDEntry");
	window->userLoginEntry=yon_gtk_builder_get_widget(builder,"userLoginEntry");
	window->userGroupsEntry=yon_gtk_builder_get_widget(builder,"userGroupsEntry");
	window->UserAdditionalGroupsButton=yon_gtk_builder_get_widget(builder,"AdditionalGroupsButton");
	window->UserCancelButton=yon_gtk_builder_get_widget(builder,"UserCancelButton");
	window->UserOkButton=yon_gtk_builder_get_widget(builder,"UserOkButton");
	window->AdditionalGroupsButton=yon_gtk_builder_get_widget(builder,"AdditionalGroupsButton");
	window->UnuniqueGIDCheck=yon_gtk_builder_get_widget(builder,"UnuniqueGIDCheck");
	window->SystemGroupCheck=yon_gtk_builder_get_widget(builder,"SystemGroupCheck");
	window->PasswordCombo=yon_gtk_builder_get_widget(builder,"PasswordCombo");
	window->PasswordEntry=yon_gtk_builder_get_widget(builder,"PasswordEntry");
	window->ChangePasswordButton=yon_gtk_builder_get_widget(builder,"ChangePasswordButton");
	window->userTitleNameLabel=yon_gtk_builder_get_widget(builder,"userTitleNameLabel");
	window->AdminGroupsEntry=yon_gtk_builder_get_widget(builder,"AdminGroupsEntry");
	window->AdminGroupsButton=yon_gtk_builder_get_widget(builder,"AdminGroupsButton");
	window->GroupaddShutdownCheck=yon_gtk_builder_get_widget(builder,"GroupaddShutdownCheck");
	window->groupExtraOptionsEntry=yon_gtk_builder_get_widget(builder,"groupExtraOptionsEntry");
	window->MainNotebook=yon_gtk_builder_get_widget(builder,"MainNotebook");
	window->last_gid=NULL;
	
	yon_entry_set_pattern(GTK_ENTRY(window->userLoginEntry),"[a-zA-Z_][a-zA-Z0-9_.-]{1,}");

	gtk_window_set_title(GTK_WINDOW(window->CreateGroupWindow),GROUPS_TITLE_LABEL);

	yon_gtk_entry_block_symbols(GTK_ENTRY(window->userLoginEntry),":\n");
		on_GID_update(NULL,window);
	dictionary *entry_dict=NULL;
	yon_dictionary_add_or_create_if_exists_with_data(entry_dict,"combo",window->PasswordCombo);
	yon_dictionary_add_or_create_if_exists_with_data(entry_dict,"entry",window->PasswordEntry);
	yon_window_config_custom_window_setup(GTK_WINDOW(window->CreateGroupWindow),"GroupAddWindow");
	g_signal_connect(G_OBJECT(window->userUIDAutoCheck),"clicked",G_CALLBACK(yon_gtk_widget_set_sensitive_from_toggle_button_inversed),window->userUIDEntry);
	g_signal_connect(G_OBJECT(window->ChangePasswordButton),"clicked",G_CALLBACK(on_password_change),entry_dict);
	g_signal_connect(G_OBJECT(window->PasswordCombo),"changed",G_CALLBACK(on_password_combo_changed),window->ChangePasswordButton);
	g_signal_connect(G_OBJECT(window->UserCancelButton),"clicked",G_CALLBACK(on_subwindow_close),NULL);
	g_signal_connect(G_OBJECT(window->UserAdditionalGroupsButton),"clicked",G_CALLBACK(on_user_choose),window->userGroupsEntry);
	g_signal_connect(G_OBJECT(window->AdminGroupsButton),"clicked",G_CALLBACK(on_user_choose),window->AdminGroupsEntry);
	g_signal_connect(G_OBJECT(window->userUIDAutoCheck),"toggled",G_CALLBACK(on_GID_update),window);
	g_signal_connect(G_OBJECT(window->SystemGroupCheck),"toggled",G_CALLBACK(on_GID_update),window);
	g_signal_connect(G_OBJECT(window->userUIDAutoCheck),"toggled",G_CALLBACK(yon_gtk_toggle_button_set_inactive_from_toggle_button),window->SystemGroupCheck);
	g_signal_connect(G_OBJECT(window->userUIDAutoCheck),"toggled",G_CALLBACK(yon_gtk_widget_set_sensitive_from_toggle_button),window->SystemGroupCheck);
	g_signal_connect(G_OBJECT(window->userUIDAutoCheck),"toggled",G_CALLBACK(yon_gtk_toggle_button_set_inactive_from_toggle_button_inversed),window->UnuniqueGIDCheck);
	g_signal_connect(G_OBJECT(window->userUIDAutoCheck),"toggled",G_CALLBACK(yon_gtk_widget_set_sensitive_from_toggle_button_inversed),window->UnuniqueGIDCheck);
	g_signal_connect(G_OBJECT(window->UnuniqueGIDCheck),"toggled",G_CALLBACK(on_system_parameter_changed),window);
	g_signal_connect(G_OBJECT(window->SystemGroupCheck),"toggled",G_CALLBACK(on_system_parameter_changed),window);
	g_signal_connect(G_OBJECT(window->userUIDEntry),"insert-text",G_CALLBACK(yon_on_text_insert_only_digits),NULL);
return window;
}



void on_GID_update(GtkWidget *, ubl_settings_usergroups_group_creation_window *window){
	if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->userUIDAutoCheck))){
		if (window->last_gid){
			gtk_entry_set_text(GTK_ENTRY(window->userUIDEntry),window->last_gid);
		} else {
			int config_size=0;
			int final_size=0;
			config_str config_groups = yon_config_get_all_by_key(GROUPADD_parameter,&config_size);
			yon_char_parsed_prepend_strings(config_groups,config_size,":");
			config_str final = yon_char_parsed_merge(main_config.groups,main_config.groups_size,config_groups,config_size,&final_size);
			long prev_busy=gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->SystemGroupCheck))?0:main_config.MINGID;

			int minimum = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->SystemGroupCheck))?0:main_config.MINGID;
			int maximum = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->SystemGroupCheck))?68000:main_config.MAXGID;
			for (int i=0;i<final_size;i++){
				int parsed_size;
				config_str parsed = yon_char_parse(final[i],&parsed_size,":");
				if (parsed_size>2&&minimum<atol(parsed[2])&&atol(parsed[2])<maximum){
					if (atol(parsed[2])>prev_busy){
						prev_busy=atol(parsed[2]);
					}
				}
				yon_char_parsed_free(parsed, parsed_size);
			}
			gtk_entry_set_text(GTK_ENTRY(window->userUIDEntry),yon_char_from_long(prev_busy+1));
		}
	} else {
		gtk_entry_set_text(GTK_ENTRY(window->userUIDEntry),"");
	}
}

void on_group_save(GtkWidget *self, dictionary *dict){
	main_window *widgets = yon_dictionary_get_data(dict->first,main_window*);
	ubl_settings_usergroups_group_creation_window *window = yon_dictionary_get_data(dict->first->next,ubl_settings_usergroups_group_creation_window*);
	char *final_string = NULL;
	char *group_name = NULL;
	char *group_users = NULL;
	char *gid = NULL;
	char *non_unique = NULL;
	char *gsystem = NULL;
	char *admins = NULL;
	char *password = NULL;
	int gid_active = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->userUIDAutoCheck));
	if (gid_active){
		gid="x";
	} else {
		gid = (char*)gtk_entry_get_text(GTK_ENTRY(window->userUIDEntry));
		if (yon_char_is_empty(gid)){
			yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
			gtk_notebook_set_current_page(GTK_NOTEBOOK(window->MainNotebook),0);
			yon_ubl_status_highlight_incorrect(window->userUIDEntry);
			return;
		}
	
	
		if (!yon_char_is_empty(window->last_gid)&&strcmp(gid,window->last_gid)){
			int config_size=0;
			int final_size=0;
			config_str config_users = yon_config_get_all_by_key(GROUPADD_SEARCH_macro,&config_size);
			config_str final = yon_char_parsed_merge(main_config.groups,main_config.groups_size,config_users,config_size,&final_size);
			if (!gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->UnuniqueGIDCheck))){
				int found=0;
				char *uid_string = (char*)gtk_entry_get_text(GTK_ENTRY(window->userUIDEntry));
				for (int i=0;i<final_size;i++){
					int parsed_size;
					config_str parsed = yon_char_parse(final[i],&parsed_size,":");
					if (parsed_size>2&&!strcmp(parsed[2],uid_string)){
						if (yon_char_is_empty(window->last_gid)||(!yon_char_is_empty(window->last_gid)&&strcmp(parsed[2],window->last_gid))){
							found = yon_char_parsed_check_exist(config_users,config_size,final[i])>-1?1:2;
							break;
						}
					}
					if (parsed_size) yon_char_parsed_free(parsed,parsed_size);
				}
				if (found){
					yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),found==1?GID_ALREADY_EXIST_CONFIG_LABEL:GID_ALREADY_EXIST_SYSTEM_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
					yon_ubl_status_highlight_incorrect(window->userUIDEntry);
					gtk_notebook_set_current_page(GTK_NOTEBOOK(window->MainNotebook),0);
					return;
				}
			}
		}
	}

	group_name = (char*)gtk_entry_get_text(GTK_ENTRY(window->userLoginEntry));
	if (group_name[0]>'0'&&group_name[0]<'9'){
			yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),GROUP_BEGINS_WITH_DIGIT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
			yon_ubl_status_highlight_incorrect(window->userLoginEntry);
			return;
	}
	if (yon_char_is_empty(group_name)){
			yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
			gtk_notebook_set_current_page(GTK_NOTEBOOK(window->MainNotebook),0);
			yon_ubl_status_highlight_incorrect(window->userLoginEntry);
			return;
	}
	{
		GtkTreeIter iter;
		GtkTreeModel *model = GTK_TREE_MODEL(widgets->GroupsList);
		// char *edit_status = g_object_get_data(G_OBJECT(window->CreateGroupWindow),"edit state");
		for_iter(model,&iter){
			char *cur;
			gtk_tree_model_get(model,&iter,1, &cur,-1);
			if (!yon_char_is_empty(cur)&&!strcmp(cur,group_name)){
				GtkTreeIter child,sort;
				gtk_tree_model_filter_convert_child_iter_to_iter(GTK_TREE_MODEL_FILTER(widgets->ConfigGroupsFilter),&child,&iter);
				gtk_tree_model_sort_convert_child_iter_to_iter(GTK_TREE_MODEL_SORT(widgets->ConfigGroupsSort),&sort,&child);
				if (!gtk_tree_selection_iter_is_selected(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->GroupsTree)),&sort)){
					
					yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),GROUP_EXIST_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
					yon_ubl_status_highlight_incorrect(window->userLoginEntry);
					gtk_notebook_set_current_page(GTK_NOTEBOOK(window->MainNotebook),0);
					return;
				}
			}
		}
	}
	
	group_users = (char*)gtk_entry_get_text(GTK_ENTRY(window->userGroupsEntry));
	
	admins = (char*)gtk_entry_get_text(GTK_ENTRY(window->AdminGroupsEntry));
	int non_unique_active = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->UnuniqueGIDCheck));
	if(non_unique_active){
		non_unique="--non-unique";
	} else non_unique="";
	
	int gsystem_active = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->SystemGroupCheck));
	if(gsystem_active){
		gsystem="--system";
	} else gsystem="";
	
	int shutdown_sync_active = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(window->GroupaddShutdownCheck));
	if (shutdown_sync_active){
		char *final_command = yon_config_parameter_prepare_command(dull_parameter_get_command,NULL,"users",GROUPADD_SYNC(group_name));
		yon_config_register(GROUPADD_SYNC(group_name),final_command,"shutdown");
	} else {
		yon_config_remove_by_key(GROUPADD_SYNC(group_name));
	}


	int password_active = gtk_combo_box_get_active(GTK_COMBO_BOX(window->PasswordCombo));
	if (password_active == 0){
		password = "";
	} else if (password_active ==5){
		password = " ";
	} else if (password_active == 1){
		password = (char*)gtk_entry_get_text(GTK_ENTRY(window->PasswordEntry));
		if (yon_char_is_empty(password)){
				yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
				gtk_notebook_set_current_page(GTK_NOTEBOOK(window->MainNotebook),0);
				yon_ubl_status_highlight_incorrect(window->PasswordEntry);
				return;
		}
	} else if (password_active==2){
			password = "!*";
	} else if (password_active ==3){
		password = (char*)gtk_entry_get_text(GTK_ENTRY(window->PasswordEntry));
		if (password[0]!='!') {
			char *temp = yon_char_append("!",password);
			password=temp;
		}
	} else if (password_active == 4){
		password = yon_char_new((char*)gtk_entry_get_text(GTK_ENTRY(window->PasswordEntry)));
		if (yon_char_is_empty(password)){
			yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),EMPTY_IMPORTANT_LABEL,5,BACKGROUND_IMAGE_FAIL_TYPE);
			yon_ubl_status_highlight_incorrect(window->PasswordEntry);
				gtk_notebook_set_current_page(GTK_NOTEBOOK(window->MainNotebook),0);
			return;
		}
		if (password[0]=='!'){
			free(yon_char_divide(password,0));
		}
	}
	final_string = yon_char_unite(yon_char_return_if_exist(group_users,""),
	":",yon_char_return_if_exist(gid,"x"),
	":",yon_char_return_if_exist(non_unique,""),
	yon_char_return_if_exist(gsystem,""),
	":",yon_char_return_if_exist(admins,""),
	":",yon_char_return_if_exist(password,""),
	NULL);
		char *final_command = yon_config_parameter_prepare_command(dull_parameter_get_command,NULL,"users",GROUPADD_SYNC(group_name));
	yon_config_register(GROUPADD(group_name),final_command,final_string);
	yon_interface_update(widgets);
	on_subwindow_close(self);
}

void on_group_delete_toggled(GtkWidget *,gchar* path,yon_confirmation_window *window){
	int found=0;
	GtkTreeModel *model = GTK_TREE_MODEL(window->list);
	GtkTreeIter iter;
	char *target;
	gtk_tree_model_get_iter_from_string(model,&iter,path);
	gtk_tree_model_get(model,&iter,1,&target,-1);
	char *parameter = config(GROUPADD(target));
	int size;
	config_str parsed = yon_char_parse(parameter,&size,":");
	int users_size;
	config_str users = yon_config_get_all_by_key(USERADD_SEARCH_macro,&users_size);
	for (int i=0;i<users_size;i++){
		int parsed_user_size;
		char *name = yon_char_divide_search(users[i],"=",-1);
		free(yon_char_divide_search(name,"[",-1));
		name[strlen(name)-1]='\0';
		config_str user_parsed = yon_char_parse(users[i], &parsed_user_size,":");
		
		int compare_size;
		config_str compare_group = yon_config_load(get_group_info_command(user_parsed[2]),&compare_size);
		int compare_parsed_size;
		
		config_str compare_parsed = yon_char_parse(compare_group[0],&compare_parsed_size,":");
		if (!strcmp(compare_parsed[1],parsed[1])){
			found = 1;
		}

	}
	if (found ==1 ){
		yon_ubl_status_box_spawn(GTK_CONTAINER(window->StatusBox),"",0,BACKGROUND_IMAGE_INFO_TYPE);
	}
	
}

void yon_group_delete_confirmation_open(main_window *widgets){
	yon_confirmation_window *window = yon_delete_confirmation_new();
	gtk_window_set_transient_for(GTK_WINDOW(window->Window),GTK_WINDOW(widgets->Window));
	// g_signal_connect(G_OBJECT(window->DeleteCell),"toggled",G_CALLBACK(on_group_delete_toggled),window);
	GtkTreeIter iter,itar;
	dictionary *dict = NULL;
	gtk_label_set_text(GTK_LABEL(window->TitleLabel),DELETE_GROUP_CONFIRMATION_CONFIRM_LABEL);
	gtk_tree_view_column_set_title(window->UserCell,GROUP_LABEL);
	gtk_label_set_text(GTK_LABEL(window->HatLabel),DELETE_GROUP_CONFIRMATION_TITLE_LABEL);
	gtk_tree_view_column_set_visible(gtk_tree_view_get_column(GTK_TREE_VIEW(window->DeletionTree),2),0);
	gtk_tree_view_column_set_visible(gtk_tree_view_get_column(GTK_TREE_VIEW(window->DeletionTree),3),0);
	gtk_tree_view_column_set_visible(gtk_tree_view_get_column(GTK_TREE_VIEW(window->DeletionTree),4),0);
	yon_dictionary_add_or_create_if_exists_with_data(dict,"widgets",widgets);
	yon_dictionary_add_or_create_if_exists_with_data(dict,"window",window);
	g_signal_connect(G_OBJECT(window->AcceptButton),"clicked",G_CALLBACK(yon_group_delete_confirmation_save),dict);
	GtkTreeModel *model = GTK_TREE_MODEL(widgets->GroupsList);
	GList *list = gtk_tree_selection_get_selected_rows(gtk_tree_view_get_selection(GTK_TREE_VIEW(widgets->GroupsTree)),&model);
	int chosen_size=0;
	config_str chosen = NULL;
	for (guint i=0;i<g_list_length(list);i++){
		char *current;
		gtk_tree_model_get_iter(model,&iter,(GtkTreePath*)g_list_nth_data(list,i));
		gtk_tree_model_get(model,&iter,1,&current,-1);
		yon_char_parsed_add_or_create_if_exists(chosen,&chosen_size,current);
	}
	int valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(widgets->GroupsList),&iter);
	for (;valid;valid=gtk_tree_model_iter_next(GTK_TREE_MODEL(widgets->GroupsList),&iter)){
		char *name;
		gtk_tree_model_get(GTK_TREE_MODEL(widgets->GroupsList),&iter,1,&name,-1);
		gtk_list_store_append(window->list,&itar);
		gtk_list_store_set(window->list,&itar,0,yon_char_parsed_check_exist(chosen,chosen_size,name)>-1?1:0,1,name,-1);
		
		free(name);
	}
	gtk_widget_show(window->Window);
}

void yon_group_delete_confirmation_save(GtkWidget *self, dictionary *dict){
	GtkTreeIter iter,itar;
	main_window *widgets = yon_dictionary_get_data(dict->first,main_window*);
	yon_confirmation_window *window = yon_dictionary_get_data(dict->first->next,yon_confirmation_window*);
	int valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(widgets->GroupsList),&iter);
	for (;valid;valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(widgets->GroupsList),&iter)){
		char *name;
		gtk_tree_model_get(GTK_TREE_MODEL(widgets->GroupsList),&iter,1,&name,-1);
		int valid2 = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(window->list),&itar);
		for (;valid2;valid2 = gtk_tree_model_iter_next(GTK_TREE_MODEL(window->list),&itar)){
			char *name_check;
			int delete;
			gtk_tree_model_get(GTK_TREE_MODEL(window->list),&itar,0,&delete,1,&name_check,-1);
			if (!strcmp(name,name_check)&&delete){
				yon_config_remove_by_key(GROUPADD(name));
				yon_config_remove_by_key(GROUPADD_SYNC(name));
				valid=0;
				break;
			}
		}
	}
	yon_interface_update(widgets);
		
	on_subwindow_close(self);
}