#include <gtk/gtk.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#include "callbacks.h"
#include "support.h"
#include "defines.h"
#include "serial.h"
#include "fileurl.h"

void on_BTN_Prog_clicked (void) {
    unsigned char buf[21];
    char displayed_text[MAX_LENGHT],currentsat_name[MAX_LENGHT];
    int i,nbbyte,nbsat,idx,test,temp;
    sat *currentsat;

    strcpy(displayed_text,"\n\r*******************************\n\r");
    strcat(displayed_text,"Programming...");
    InsertText(OUT_Display,displayed_text);
    if(OpenCOM(gtk_combo_box_text_get_active_text(GTK_COMBO_BOX(SELECT_Port)),atol(gtk_combo_box_text_get_active_text(GTK_COMBO_BOX(SELECT_Speed))))) {
        if(WriteCOM("READ  \n",sizeof("READ  \n")-1,&nbbyte)) {
            ReadCOM(&buf,20,&nbbyte);
            if(nbbyte!=2) {
                strcpy(displayed_text,"******* ERROR *******\n\rCan't open port !");
                InsertText(OUT_Display,displayed_text);
            }
            else {
                nbsat=(int)buf[1];
                idx=(int)buf[0];
                if(nbsat==0) { strcpy(displayed_text,"No sats previously programmed"); }
                else { sprintf(displayed_text,"%i satellite(s) previously programmed\n\rover %i memory places.",nbsat,idx+1); }
                InsertText(OUT_Display,displayed_text);
                test=TRUE;
                for(i=0;i<idx+1;i++) {
                    strcpy((char*)buf,"ERASE ");
                    buf[6]=i+1;
                    buf[7]='\n';
                    if(WriteCOM(buf,8,&nbbyte)) {
                        ReadCOM(&buf,20,&nbbyte);
                        if(strncmp("OK ",(char*)buf,3)!=0) { test=FALSE; }
                    }
                    else { test=FALSE; }
                }
                if(test!=TRUE) { strcpy(displayed_text,"******* ERROR *******\n\rProblem while erasing sat !"); }
                else {
                    if(nbsat!=0) { strcpy(displayed_text,"Memory cleared."); }
                    else { strcpy(displayed_text,"Clearing memory not required."); }
                }
                InsertText(OUT_Display,displayed_text);
                if(test==TRUE) {
                    currentsat=filecontent;
                    while(currentsat->prev!=NULL) {
                        currentsat=currentsat->prev;
                    }
                    test=FALSE;
                    while(currentsat!=NULL) {
                        strcpy(currentsat_name,currentsat->line[0]);
                        temp=strlen(currentsat_name);
                        currentsat_name[temp-1]='\0';
                        for(i=0;i<3;i++) { WriteCOM(currentsat->line[i],strlen(currentsat->line[i]),&nbbyte); }
                        WriteCOM(currentsat->line_freq,11,&nbbyte);
                        ReadCOM(&buf,20,&nbbyte);
                        for(i=0;i<nbbyte;i++) { g_print("%.2X ",buf[i]); }
                        g_print("\n\r");
                        if(strncmp(currentsat_name,(char*)buf,temp-1)!=0 || buf[temp]==ERR_BAD_CHECKSUM || buf[temp]==ERR_FLASH_WRITE || buf[temp]==ERR_NO_FREE_SPACE) {
                            strcpy(displayed_text,"******* ERROR *******\n\rProblem while programming ");
                            strcat(displayed_text,currentsat_name);
                            strcat(displayed_text," datas !");
                            test=TRUE;
                        }
                        else {
                            strcpy(displayed_text,currentsat_name);
                            strcat(displayed_text," programmed.");
                        }
                        InsertText(OUT_Display,displayed_text);
                        currentsat=currentsat->next;
                    }
                    if(test==FALSE) { WriteCOM("STOP  \n",sizeof("STOP  \n")-1,&nbbyte); }
                }
            }
        }
        CloseCOM();
    }
}

void on_BTN_Quit_clicked (void) {
    gtk_main_quit();
}

void on_BTN_Load_clicked (void) {
    char currentpath[MAX_LENGHT_DIRECTORY],update_url[MAX_LENGHT],current_line[MAX_LENGHT];
    char displayed_text[MAX_LENGHT],stmp[KEP_MAX_CHARS],stmp1[KEP_MAX_CHARS],stmp2[KEP_MAX_CHARS];
    sat *prevsat;
    FILE *updateptr;
    int i,all_sat_ok,nbsat,tmp;
    URL_FILE *urlptr;
    GtkWidget *p_dialog = NULL;

    while(filecontent!=NULL) {
        prevsat=filecontent->prev;
        free(filecontent);
        filecontent=prevsat;
    }

    getcwd(currentpath,MAX_LENGHT_DIRECTORY);
    g_print("%s\n\r",currentpath);
    strcat(currentpath,INFO_FILE);
    updateptr=fopen(currentpath,"r");
    if(updateptr!=NULL) {
        fgets(update_url,MAX_LENGHT,updateptr);
        if(strncmp(update_url,"[UPDATE_URL]",12)==0) {
            fgets(update_url,MAX_LENGHT,updateptr);
            tmp = strlen(update_url);
            update_url[tmp-1] = 0;
            urlptr=url_fopen(update_url,"r");
            if(urlptr!=NULL) {
                fgets(current_line,MAX_LENGHT,updateptr);
                while(strncmp(current_line,"[SATS]",6)!=0 && feof(updateptr)==0) { fgets(current_line,MAX_LENGHT,updateptr); }
                strcpy(displayed_text,"******** ");
                strcat(displayed_text,"LOADING");
                strcat(displayed_text," ********");
                InsertText(OUT_Display,displayed_text);

                all_sat_ok=TRUE;
                nbsat=0;
                url_fclose(urlptr);
                while(fgets(stmp,KEP_MAX_CHARS,updateptr)!=NULL && nbsat<MAX_SATS) {
                    urlptr=url_fopen(update_url,"r");
                    while(strcmp(stmp,stmp1)!=0 && url_feof(urlptr)==0) {
                        url_fgets(stmp1,KEP_MAX_CHARS,urlptr);
                    }
                    fgets(stmp2,KEP_MAX_CHARS,updateptr);
                    strcpy(displayed_text,stmp);
                    displayed_text[strlen(displayed_text)-1]='\0';
                    if(strcmp(stmp,stmp1)!=0) {
                        strcat(displayed_text," not found");
g_print("%s\n\r",displayed_text);
                        InsertText(OUT_Display,displayed_text);
                        all_sat_ok=FALSE;
                    }
                    else {
                        strcat(displayed_text," OK");
g_print("%s\n\r",displayed_text);
                        InsertText(OUT_Display,displayed_text);

                        prevsat=filecontent;
                        filecontent=malloc(sizeof(struct sat));
                        filecontent->prev=prevsat;
                        filecontent->next=NULL;
                        if(prevsat!=NULL) { prevsat->next=filecontent; }

                        strcpy(filecontent->line[0],stmp1);
                        url_fgets(filecontent->line[1],KEP_MAX_CHARS,urlptr);
                        url_fgets(filecontent->line[2],KEP_MAX_CHARS,urlptr);
                        filecontent->line_freq[0]='3';
                        filecontent->line_freq[1]=' ';
g_print("stmp2: %s\n\r",stmp2);
                        for(i=0;i<3;i++) {
                            tmp=(unsigned char)stmp2[i*2]-'0';
                            tmp*=16;
                            tmp+=(unsigned char)stmp2[i*2+1]-'0';
                            filecontent->line_freq[i+2]=tmp;
                            tmp=(unsigned char)stmp2[i*2+9]-'0';
                            tmp*=16;
                            tmp+=(unsigned char)stmp2[i*2+10]-'0';
                            filecontent->line_freq[i+6]=tmp;
                        }
                        filecontent->line_freq[5]=0;
                        filecontent->line_freq[9]=0;
                        /*********************************
                        mode FM : 0x01 USB : 0x02 LSB : 0x03 FM PL67 : 0x04
                        décalage 0 : 0x10 + : 0x20 - : 0x30
                        *********************************/
                        switch(stmp2[6]) {
                            case 'F':   filecontent->line_freq[5]+=0x01;
                                        break;
                            case 'U':   filecontent->line_freq[5]+=0x02;
                                        break;
                            case 'L':   filecontent->line_freq[5]+=0x03;
                                        break;
                            case 'P':   filecontent->line_freq[5]+=0x04;
                                        break;
                        }
                        switch(stmp2[7]) {
                            case '0':   filecontent->line_freq[5]+=0x10;
                                        break;
                            case '+':   filecontent->line_freq[5]+=0x20;
                                        break;
                            case '-':   filecontent->line_freq[5]+=0x30;
                                        break;
                        }
                        switch(stmp2[15]) {
                            case 'F':   filecontent->line_freq[9]+=0x01;
                                        break;
                            case 'U':   filecontent->line_freq[9]+=0x02;
                                        break;
                            case 'L':   filecontent->line_freq[9]+=0x03;
                                        break;
                            case 'P':   filecontent->line_freq[9]+=0x04;
                                        break;
                        }
                        switch(stmp2[16]) {
                            case '0':   filecontent->line_freq[9]+=0x10;
                                        break;
                            case '+':   filecontent->line_freq[9]+=0x20;
                                        break;
                            case '-':   filecontent->line_freq[9]+=0x30;
                                        break;
                        }
                        filecontent->line_freq[10]='\n';
for(i=0;i<11;i++) { g_print("%X ",filecontent->line_freq[i]); }
g_print("\n\r");
                        nbsat++;
                    }
                    url_fclose(urlptr);
                }
                if(!all_sat_ok) {
                    p_dialog=gtk_message_dialog_new(NULL,GTK_DIALOG_MODAL,GTK_MESSAGE_QUESTION,GTK_BUTTONS_YES_NO,"Not all sats required in sats.txt found.\n\rPlease verify sats' names.\n\r Enable programming with only found sats ?");
                    gtk_window_set_position(GTK_WINDOW(p_dialog),GTK_WIN_POS_CENTER);
                    tmp=gtk_dialog_run(GTK_DIALOG(p_dialog));
                    gtk_widget_destroy (p_dialog);
                    if(tmp==GTK_RESPONSE_YES) { gtk_widget_set_sensitive(BTN_Prog,TRUE); }
                }
                else { gtk_widget_set_sensitive(BTN_Prog,TRUE); }
            }
            else {
                strcpy(displayed_text,"******* ERROR *******\n\r");
                strcat(displayed_text,"Can't open URL for update : \n\r");
                strcat(displayed_text,update_url);
                InsertText(OUT_Display,displayed_text);
            }
        }
        else { InsertText(OUT_Display,"******* ERROR *******\n\rsats.txt corrupted..."); }
        fclose(updateptr);
    }
    else {
        InsertText(OUT_Display,"******* ERROR *******\n\rCan't open sats.txt in current directory");
    }
}

void on_BTN_Filechoose_selection_changed(void) {
    char filename[MAX_LENGHT_FILENAME],currentpath[MAX_LENGHT_DIRECTORY],*folder,*path,current_line[MAX_LENGHT];
    char displayed_text[MAX_LENGHT],stmp[KEP_MAX_CHARS],stmp1[KEP_MAX_CHARS],stmp2[KEP_MAX_CHARS];
    sat *prevsat;
    FILE *updateptr,*fileptr;
    int i,all_sat_ok,nbsat,tmp;
    GtkWidget *p_dialog = NULL;

    while(filecontent!=NULL) {
        prevsat=filecontent->prev;
        free(filecontent);
        filecontent=prevsat;
    }

    folder=gtk_file_chooser_get_current_folder(GTK_FILE_CHOOSER(BTN_Filechoose));
    tmp=strlen(folder);
    path=gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(BTN_Filechoose));
    strncpy(filename,path+tmp+1,MAX_LENGHT_FILENAME);

    getcwd(currentpath,MAX_LENGHT_DIRECTORY);
    g_print("%s\n\r",currentpath);
    strcat(currentpath,INFO_FILE);
    updateptr=fopen(currentpath,"r");
    if(updateptr!=NULL) {
        fgets(stmp,MAX_LENGHT,updateptr);
        if(strncmp(stmp,"[UPDATE_URL]",12)==0) {
            fgets(stmp,MAX_LENGHT,updateptr);
            fileptr=fopen(path,"r");
            if(fileptr!=NULL) {
                fgets(current_line,MAX_LENGHT,updateptr);
                while(strncmp(current_line,"[SATS]",6)!=0 && feof(updateptr)==0) { fgets(current_line,MAX_LENGHT,updateptr); }
                strcpy(displayed_text,"*********** ");
                strcat(displayed_text,"LOADING");
                strcat(displayed_text," ***********");
                InsertText(OUT_Display,displayed_text);

                all_sat_ok=TRUE;
                nbsat=0;
                fclose(fileptr);
                while(fgets(stmp,KEP_MAX_CHARS,updateptr)!=NULL && nbsat<MAX_SATS) {
                    fileptr=fopen(path,"r");
                    while(strcmp(stmp,stmp1)!=0 && feof(fileptr)==0) { fgets(stmp1,KEP_MAX_CHARS,fileptr); }
                    fgets(stmp2,KEP_MAX_CHARS,updateptr);
                    strcpy(displayed_text,stmp);
                    displayed_text[strlen(displayed_text)-1]='\0';
                    if(strcmp(stmp,stmp1)!=0) {
                        strcat(displayed_text," not found");
g_print("%s\n\r",displayed_text);
                        InsertText(OUT_Display,displayed_text);
                        all_sat_ok=FALSE;
                    }
                    else {
                        strcat(displayed_text," OK");
g_print("%s\n\r",displayed_text);
                        InsertText(OUT_Display,displayed_text);

                        prevsat=filecontent;
                        filecontent=malloc(sizeof(struct sat));
                        filecontent->prev=prevsat;
                        filecontent->next=NULL;
                        if(prevsat!=NULL) { prevsat->next=filecontent; }

                        strcpy(filecontent->line[0],stmp1);
                        fgets(filecontent->line[1],KEP_MAX_CHARS,fileptr);
                        fgets(filecontent->line[2],KEP_MAX_CHARS,fileptr);
                        filecontent->line_freq[0]='3';
                        filecontent->line_freq[1]=' ';
                        for(i=0;i<4;i++) {
                            tmp=(unsigned char)stmp2[i*2+2]-'0';
                            tmp*=16;
                            tmp+=(unsigned char)stmp2[i*2+3]-'0';
                            filecontent->line_freq[i+2]=tmp;
                            tmp=(unsigned char)stmp2[i*2+11]-'0';
                            tmp*=16;
                            tmp+=(unsigned char)stmp2[i*2+12]-'0';
                            filecontent->line_freq[i+6]=tmp;
                        }
                        filecontent->line_freq[10]='\n';
                        nbsat++;
                    }
                    fclose(fileptr);
                }
                if(!all_sat_ok) {
                    p_dialog=gtk_message_dialog_new(NULL,GTK_DIALOG_MODAL,GTK_MESSAGE_QUESTION,GTK_BUTTONS_YES_NO,"Not all sats required in sats.txt found.\n\rPlease verify sats' names.\n\r Enable programming with only found sats ?");
                    gtk_window_set_position(GTK_WINDOW(p_dialog),GTK_WIN_POS_CENTER);
                    tmp=gtk_dialog_run(GTK_DIALOG(p_dialog));
                    gtk_widget_destroy (p_dialog);
                    if(tmp==GTK_RESPONSE_YES) { gtk_widget_set_sensitive(BTN_Prog,TRUE); }
                }
                else { gtk_widget_set_sensitive(BTN_Prog,TRUE); }
            }
            else {
                strcpy(displayed_text,"******* ERROR *******\n\r");
                strcat(displayed_text,"Can't open selected for update : \n\r");
                strcat(displayed_text,path);
                InsertText(OUT_Display,displayed_text);
            }
        }
        else { InsertText(OUT_Display,"******* ERROR *******\n\rsats.txt corrupted..."); }
        fclose(updateptr);
    }
    else {
        InsertText(OUT_Display,"******* ERROR *******\n\rCan't open sats.txt in current directory");
    }
}
