#ifndef UBL_UTILS
#define UBL_UTILS
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <pthread.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pwd.h>
#include <locale.h>
#include <gtk/gtk.h>
#include <gtk/gtkx.h>
#define try bool __HadError=false;
#define catch(x) ExitJmp:if(__HadError)
#define throw(x) {__HadError=true;goto ExitJmp;}

#include "../../compile/ubl-cmake.h"
#ifdef WEBKIT_FOUND
    #include <webkit2/webkit2.h>
#endif 
#define DesktopPath "/usr/share/applications/"

#define for_dictionaries(obj, obj1) for (obj = obj1->first; obj != NULL; obj = obj->next)

#define new(type) malloc(sizeof(type))
#define new_arr(type,size) malloc(sizeof(type)*size)

#define get_home_dir_command yon_char_unite("getent passwd \"",yon_ubl_root_user_get(),"\" | cut -d: -f6",NULL)

typedef enum
{
    #ifdef __GTK_H__
    DICTIONARY_GTK_WIDGETS_TYPE,
    #endif
    DICTIONARY_OTHER_TYPE=0,
    DICTIONARY_CHAR_TYPE,
    DICTIONARY_INT_TYPE,
    DICTIONARY_BOOL_TYPE,

} DICT_TYPE;

typedef struct dictionary
{
    char *key;
    void *data;
    struct dictionary *next;
    struct dictionary *prev;
    struct dictionary *first;
    DICT_TYPE data_type;
    int flag1;
} dictionary;

typedef struct apps
{
    char *Name;
    int Type;
    char *Categories;
    char *Exec;
    char *Icon;
    int Pluggable;
    int DualPluggable;
} apps;

typedef char** config_str;

static dictionary *__yon__config__strings = NULL;
#define check_config if(__yon__config__strings&&__yon__config__strings->data_type==DICTIONARY_CHAR_TYPE)

#define config(key) yon_config_get_by_key(key) 

#define for_config dictionary temp = NULL; for_dictionary(temp,__yon__config__strings)

#define yon_remalloc(pointer, size) (!pointer) ? malloc(size) : realloc(pointer, size)
// dictionary functions

/**yon_dictionary_get_data(dictionary, type)
 * [EN]
 * Gets data from dictionary.
 * [dictionary] is dictionary, from which data should be extracted;
 * [type] is type of data, [dictionary] contains.
 * [RU]
 * Возвращает данные из словаря.
 * [dictionary] - словарь из которого достаются данные.
 * [type] - тип данных, хранящихся в словаре [dictionary].
*/
#define yon_dictionary_get_data(dictionary, type) ((type)dictionary->data)

/**yon_dictionary_add_or_create_if_exists_with_data(dict,key,data)
 * [EN]
 * 
 * [RU]
 * Добавляет элемент словаря в конец словаря [dict] c ключом [key] и данными [data].
 * Если словарь не существует, создаёт его 
*/
#define yon_dictionary_add_or_create_if_exists_with_data(dict,key,data) {if (!dict) dict=yon_dictionary_new_with_data(key,data); \
                                                                        else dict=yon_dictionary_append_with_data(dict,key,data);}

dictionary *yon_dictionary_new();

dictionary *yon_dictionary_append(dictionary *targetdict);

dictionary *yon_dictionary_get_last(dictionary *dict);

dictionary *yon_dictionary_swap(dictionary *dict, int aim);

void yon_dictionary_make_first(dictionary *dict);

void yon_dictionary_make_nth(dictionary *dict, int nth);

dictionary *yon_dictionary_new_with_data(char *key, void *data);

dictionary *yon_dictionary_append_with_data(dictionary *dict, char *key, void *data);

dictionary *yon_dictionary_connect(dictionary *old, dictionary *toconnect);

dictionary *yon_dictionary_get(dictionary **dict, char *key);

dictionary *yon_dictionary_rip(dictionary *dict);

dictionary *yon_dictionary_get_nth(dictionary *dict, int place);

void *yon_dictionary_free_all(dictionary *dictionary,void (data_manipulation)(void*));

// char functions

int yon_char_find_last(char *source, char find);

char *yon_char_append(char *source, char *append);

char *yon_char_new(char *chr);

char *yon_char_unite(char *source, ...);

char *yon_cut(char *source, int size, int startpos);

char *yon_char_divide(char *source, int dividepos);

char *yon_char_divide_search(char *source, char *dividepos, int delete_divider);

char *yon_char_from_int(int int_to_convert);

char *yon_char_replace(char *source, char *find, char*replace);

char **yon_char_parse(char *parameters, int *size, char *divider);

char **yon_char_parsed_rip(char **char_string, int *size, int item_to_delete);

int yon_char_parsed_check_exist(char **parameters, int size, char *param);

int yon_char_find_count(char *source, char *find);

int yon_char_parsed_includes_char_parsed (config_str source, config_str to_check, int source_size, int check_size);

config_str yon_char_parsed_new (int *size, ...);

void yon_char_parsed_copy(config_str *source, config_str *to_copy);

config_str yon_char_parsed_append(config_str parsed, int *size, char *string);

int yon_ubl_check_root();

char *yon_ubl_root_user_get();

char *yon_ubl_user_get_home_directory();

// parsing functions

apps *yon_apps_scan_and_parse_desktops(int *sizef);

void yon_apps_sort(apps *applist, int size);

apps *yon_apps_get_by_name(apps *applist, char *name, int size);

config_str yon_config_load(char *command, int *str_len);

int yon_config_save_registered(char *command);

char *yon_config_get_parameter(config_str parameters, int size, char *param);

int yon_config_load_register(char *command);

int yon_config_remove_by_key(char *key);

int yon_config_remove_by_data(void *data);

int yon_config_remove_element(char *key, char *deleted);

void *yon_config_get_by_key(char *key);

char *yon_config_get_key_by_data(char *data);

int yon_config_set(char *key, void *data);

int yon_config_clean();

void yon_config_register(char *key, void *data);

config_str yon_config_get_all();

// terminal-using functions

int yon_launch_app_with_arguments(char *name, char *args);

void yon_launch(char *command);

// Gtk functions

#ifdef __GTK_H__
#ifdef VTE_TERMINAL
void yon_terminal_integrated_launch(GtkWidget *place_to_show, char* command, void *endwork_function, void* endwork_function_argument);

void yon_terminal_integrated_start(GtkWidget *terminal, char* command, void *endwork_function, void* endwork_function_argument);

#endif

enum YON_TYPE{
    YON_TYPE_STRING,
    YON_TYPE_STRING_LIST,
    YON_TYPE_INT,
    YON_TYPE_BOOLEAN,
    YON_TYPE_OTHER
};

GtkWidget *yon_ubl_menu_item_about_new(char *buttonname);
GtkWidget *yon_ubl_menu_item_documentation_new(char *buttonname);

/**yon_gtk_builder_get_widget(builder, widget_name)
 * [EN]
 * Returns GtkWidget from GtkBuilder *[builder].
 * [builder] is GtkBuilder*;
 * [widget_name] is id of widget;
*/
#define yon_gtk_builder_get_widget(builder, widget_name) GTK_WIDGET(gtk_builder_get_object(builder, widget_name))

typedef struct
{
    GtkWidget *Icon;
    GtkWidget *Label;
    GtkWidget *IconView;
    GtkListStore *List;
} expander_icon_view;

void yon_window_config_setup(GtkWindow *window);

int yon_window_config_load(char *path);

config_str yon_window_config_get_section(char *section, gsize *size);

void yon_window_config_add_listener(GtkWidget *widget, char *param_name, char *widget_property, enum YON_TYPE val_type);

void yon_window_config_add_custom_parameter(char *param_name, char *section, void *tracked_value, enum YON_TYPE val_type);

void yon_window_config_erase_custom_parameter(char *param_name, char *section);

int yon_window_config_get_parameter(char *section, char *config_parameter, void *return_value, enum YON_TYPE type);

int yon_gtk_combo_box_fill(GtkWidget *combo, char **parameters,int size);

int yon_gtk_combo_box_text_find(GtkWidget *combo_box, char *text_to_find);

void yon_gtk_column_minimal_fixed_size_set(GtkTreeViewColumn *column);

int yon_gtk_icon_view_hide_empty(dictionary *icon_view_segment);

int yon_dictionary_gtk_pack_start_multiple_widgets(GtkBox *destination, gboolean expand, gboolean fill, int padding, ...);

int yon_dictionary_gtk_pack_end_multiple_widgets(GtkBox *destination, gboolean expand, gboolean fill, int padding, ...);



typedef enum
{
    BACKGROUND_IMAGE_SUCCESS_TYPE,
    BACKGROUND_IMAGE_FAIL_TYPE
} BACKGROUND_IMAGE_TYPE;

typedef struct {
    BACKGROUND_IMAGE_TYPE type;
    GtkWidget *icon;
    GtkWidget *box;
    GtkWidget *label;
    char* text_to_render;
} render_data;


/**yon_ubl_status_box_setup(render,icon,box,label)
 * [EN]
 * Sets up [render] structure of type render_data.
 * [icon] is GtkImage widget of status box for showing status icons;
 * [box] is GtkBox widget of status box for showing status color;
 * [label] is GtkLabel widget of status box for showing status text;
 * [RU]
 * Настраивает структуру [render] типа render_data.
 * [icon] - виджет типа GtkIcon в котором будут отображаться статусные иконки;
 * [box] - виджет типа GtkBox в котором будет отображаться цвет статуса;
 * [label] - виджет типа GtkLabel в котором будет отображаться текст статусного сообщения;
*/
int yon_ubl_status_box_setup(GtkWidget *icon, GtkWidget *box, GtkWidget *label);

/**yon_ubl_status_box_render(render,text,type)
 * [EN]
 * Renders message in status box;
 * [render] is render_data structure of status box;
 * [text] is text to be shown in status box;
 * [type] if type of message. Can be BACKGROUND_IMAGE_FAIL_TYPE or BACKGROUND_IMAGE_SUCCESS_TYPE
 * [RU]
 * Отображает сообщение в статусном окне.
 * [render] - структура типа render_data для нужного статусного окна;
 * [text] - текст, отображаемый в статусном окне;
 * [type] - тип сообщения. Может быть:
 * BACKGROUND_IMAGE_FAIL_TYPE (красный фон,иконка - восклицательный знак)
 * или
 * BACKGROUND_IMAGE_SUCCESS_TYPE (Жёлтный фон, иконка - галка)
*/
void yon_ubl_status_box_render(char *text, BACKGROUND_IMAGE_TYPE type);

#ifdef __cplusplus

/**yon_ubl_header_setup(overlay, head, image, imag_path)
 * [EN]
 * Sets up header of app.
 * [overlay] is overlay for app header;
 * [head] is box of header, which connects to [overlay]
 * [image] is header background image;
 * [imag_path] is path of image, shown in [image] 
 * [RU]
 * Настраивает заголовок приложения.
 * [overlay] - оверлей заголовка приложения;
 * [head] - шапка заголовка, присоединяемая к [overlay]
 * [image] - виджет картинки для заднего фона;
 * [imag_path] - путь до картинки, загружаемой в [image] 
*/
#define yon_ubl_header_setup(overlay, head, image, imag_path) _yon_ubl_header_setup(GTK_WIDGET(overlay.gobj()), GTK_WIDGET(head.gobj()), GTK_WIDGET(image.gobj()), (char *)imag_path)
#else

/**yon_ubl_header_setup(overlay, head, image, imag_path)
 * [EN]
 * Sets up header of app.
 * [overlay] is overlay for app header;
 * [head] is box of header, which connects to [overlay]
 * [image] is header background image;
 * [imag_path] is path of image, shown in [image] 
 * [RU]
 * Настраивает заголовок приложения.
 * [overlay] - оверлей заголовка приложения;
 * [head] - шапка заголовка, присоединяемая к [overlay]
 * [image] - виджет картинки для заднего фона;
 * [imag_path] - путь до картинки, загружаемой в [image] 
*/
#define yon_ubl_header_setup(overlay, head, image, imag_path) _yon_ubl_header_setup(GTK_WIDGET(overlay), GTK_WIDGET(head), GTK_WIDGET(image), (char *)imag_path)
#define yon_ubl_header_setup_resource(overlay, head, image, imag_path) _yon_ubl_header_setup_resource(GTK_WIDGET(overlay), GTK_WIDGET(head), GTK_WIDGET(image), (char *)imag_path)
#endif

void _yon_ubl_header_setup(GtkWidget *Overlay, GtkWidget *Head, GtkWidget *Image, char *image_path);

void _yon_ubl_header_setup_resource(GtkWidget *Overlay, GtkWidget *Head, GtkWidget *Image, char *image_path);

void yon_ubl_setup_sockets(GtkWidget *main_window, GtkWidget *left_window, GtkWidget *right_window, int socket_main_id, int socket_left_id, int socket_right_id);
#ifdef WEBKIT_FOUND

void yon_ubl_browser_window_open(char *link, char *browser_window_name);
#else
void yon_ubl_browser_window_open(char *link,  char *browser_window_name);
#endif
#endif
#endif