/* === === === io.c === === === */

#include "include.h"
#include "typedef.h"
#include "io.h"

CMD_GRP_LIST cmd_list;

void create_cmd_list(CMD_GRP_ENUM grp,char* get[],int n){
    if(grp == CMD_GRP_COUNT)return;
   
    CMD_LIST* newlist = (CMD_LIST*)malloc(sizeof(CMD_LIST));
    newlist->str = (char**)malloc(n*sizeof(char*));
    for(int i = 0;i<n;i++){
        newlist->str[i] = (char*)malloc((strlen(get[i])+1)*sizeof(char));
        strcpy(newlist->str[i],get[i]);
    }
    
    del_cmd_list(grp);
    cmd_list.list[grp] = newlist;
    cmd_list.list[grp]->n=n;
}

void del_cmd_list(CMD_GRP_ENUM grp){
    CMD_LIST** list = &cmd_list.list[grp];
    if((*list)==NULL) return;
    for(int i = 0; i < (*list)->n; i++)
        free((*list)->str[i]);
    free((*list)->str);
    free(*list);
}

void declarete_cmd_main(){
    create_cmd_list(CMD_MAIN,(char*[])
            {"create","input","del","show",
            "logic","edit","rand","copy",
            "exit","test"},10);
}

char buff_input(char *inbuff, char *_buff){
    
    *inbuff = 0;
    { // INPUT
        char ch;
        memset(_buff, 0, BUFF_MAX);
        while((ch=getchar())>' '&&*inbuff<BUFF_MAX){
            *(_buff+*inbuff)=(int)ch;
            (*inbuff)++;
        }
        if(ch<= 4)return -1;
        _buff[*inbuff] = '\0';
    }


    if (_buff[0]>='a' && _buff[0] <= 'z'){
        char cmd = cmd_buff(_buff,CMD_MAIN);
        if(cmd==15)return -1;
        return cmd;
    }

    return 0;
}

char cmd_buff(char* _buff,CMD_GRP_ENUM grp){
    unsigned int n = cmd_list.list[grp]->n;
    char** list = cmd_list.list[grp]->str;

    for (int i = 0;i<n;i++){
        char flag = 1;
        for(int j = 0;*(list[i]+j)!='\0';j++){
            if (_buff[j]!=*(list[i]+j)){
                flag = 0;
                break;
            }
        }
        if(flag) return i+1;
    }
    return 0;
}

char get_matrix_num(void){
    extern MATRIX_LIST matrix_l;
    char inbuff;
    char _buff[BUFF_MAX];
    while(buff_input(&inbuff,_buff)>0&&*_buff>' ');

    long int num = 0;
    char flagIsDec = 1;
    { // GetNum
        int i = 0;
        if(_buff[0]=='-'){i++;flagIsDec = -1;}
        
        for(; i<inbuff;i++)
            if(_buff[i]>= '0' && _buff[i] <= '9')
                num = (num*10) + (_buff[i]-'0');
        num *= flagIsDec;
    }
        if (num>=matrix_l.n)num = matrix_l.n;
        if (num<0)num = 0;
        return num;
}

int get_num(void){
    char inbuff;
    char _buff[BUFF_MAX];
    while(buff_input(&inbuff,_buff)>0&&*_buff>' ');

    long int num = 0;
    char flagIsDec = 1;
    { // GetNum
        int i = 0;
        if(_buff[0]=='-'){i++;flagIsDec = -1;}
        
        for(; i<inbuff;i++)
            if(_buff[i]>= '0' && _buff[i] <= '9')
                num = (num*10) + (_buff[i]-'0');
        num *= flagIsDec;
    }
        if (num>INT_MAX)num = INT_MAX;
        if (num<INT_MIN)num = INT_MIN;
        return (int)num;
}
