/*
** EPITECH PROJECT, 2018
** task01
** File description:
** I do task
*/
#include <unistd.h>
#include "lib/my_stdio.h"

extern void vfprintf_get_arg(printf_t *print, char type);
extern void vfprintf_get_base(printf_t *print, char type);
extern void vfprintf_print_arg(printf_t *print, int size);
extern int vfprintf_get_size(printf_t *print, char type);
extern int vfprintf_get_ouput_type(printf_t *print, char type);
extern int vfprintf_get_type(printf_t *print, char const *format);
extern int vfprintf_get_flags(printf_t *print, char const *format);
extern int vfprintf_get_precision(printf_t *print, char const *format);

static void vfprintf_setup_print(printf_t *print)
{
    print->type = 0;
    print->base = 10;
    print->value = 0;
    print->cursor = 0;
    print->sign = '\0';
    print->str_width = 0;
    print->nbr_width = 0;
    print->precision = 0;
    print->type = PRINT_TYPE_RESET;
    print->mode_flags = PRINT_MODE_RESET;
}

static int vfprintf_action(printf_t *print, char const *format)
{
    int read_size;
    int error;

    if (*format != '%')
        return (0);
    vfprintf_setup_print(print);
    read_size = vfprintf_get_flags(print, format);
    read_size += vfprintf_get_precision(print, format + read_size);
    read_size += vfprintf_get_type(print, format + read_size);
    vfprintf_get_base(print, *(format + read_size));
    error = vfprintf_get_ouput_type(print, *(format + read_size));
    if (error < 0)
        return (read_size + 1);
    if (error == 0)
        return (0);
    vfprintf_get_arg(print, *(format + read_size));
    vfprintf_get_size(print, *(format + read_size));
    vfprintf_print_arg(print, print->str_width);
    return (read_size + 1);
}

void my_vfprintf(int fd, char const *format, va_list ap)
{
    int read_flags;
    printf_t print;

    print.stream = fd;
    va_copy(print.ap, ap);
    while (*format != '\0'){
        read_flags = vfprintf_action(&print, format);
        if (!read_flags)
            write(fd, format++, 1);
        format += read_flags;
    }
}
