#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include "argpase.h"

char *Optarg, *Optstr;
int Optindex = 0;

OptList *Options_Creat(char *name, OptId index) {
    OptList *p;
    p = (OptList *) malloc(sizeof(OptList));
    memset(p, 0, sizeof(OptList));
    Option *opt = (Option *) malloc(sizeof(Option));
    memset(opt, 0, sizeof(Option));
    opt->name = name;
    opt->id = index;
    p->Option = opt;
    p->next = NULL;
    return p;
}

OptList *Options_CreatOpt(Option *opt) {
    OptList *p;
    p = (OptList *) malloc(sizeof(OptList));
    memset(p, 0, sizeof(OptList));
    p->Option = opt;
    p->next = NULL;
    return p;
}

void Options_Add(OptList *opts, OptList *opt) {
    OptList *p = opts;
    while (NULL != p->next) {
        p = p->next;
    }
    p->next = opt;
}

bool Options_Del(OptList *opts, char *opt) {
    //获取当前头节点的位置
    OptList *p = opts;
    OptList *prev = NULL;
    while (NULL != p->next) {
        //保存当前节点的前一个节点的指针
        prev = p;
        //然后让当前的指针继续往后移动
        p = p->next;
        //判断，找到了要删除的数据
        if (0 == strcmp(p->Option->name, opt)) {
            //两种情况，一种是普通节点，还有一种是尾节点
            if (p->next != NULL)  //普通节点的情况
            {
                prev->next = p->next;
                free(p);
            } else //尾节点的情况
            {
                prev->next = NULL; //将这个尾节点的上一个节点的指针域指向空
                free(p);
            }
            return true;
        }
    }
    return false;
}

void Options_Print(OptList *opts) {
    OptList *p = opts;
    while (NULL != p) {
        printf("Option[%d]:%s\n", p->Option->id, p->Option->name);
        p = p->next;
    }
}

OptId Options_Load(OptList *opts, char *argv[], size_t argc) {
    OptList *p = opts;
    OptId id = -2;
    while (NULL != p) {
        if (0 == strcmp(p->Option->name, argv[Optindex])) {
            Optarg = argv[Optindex + 1];
            Optstr = p->Option->name;
            id = p->Option->id;
        }
        p = p->next;
    }
    Optindex++;
    if (Optindex >= argc) {
        return -1;
    }
    return id;
}

size_t Str_To_Args(char *str, char *argv[]) {
    char *p;
    size_t argc = 0;
    size_t l = strlen(str);
    char *buf = (char *) malloc(sizeof(char) * l + 1);
    strcpy(buf, str);
    p = strtok(buf, " ");
    while (p) {
        argv[argc] = p;
        argc++;
        p = strtok(NULL, " ");
    }
    return argc;
}

