/*
** EPITECH PROJECT, 2018
** task01
** File description:
** I do task
*/
#include "../../include/lib/s_sfml.h"
#include "../../include/lib/my_graphics.h"


static void set_line_dy(polygon_t *polygon, void *ptr[], int var[6])
{
    char *empty = (char*)ptr[2];
    int *xmin = (int*)ptr[1];
    int *xmax = (int*)ptr[0];
    int cumul;
    int i;

    i = 0;
    cumul = var[3] >> 1;
    while (++i < var[3]){
        var[1] += var[5];
        cumul += var[2];
        if (cumul > var[3]){
            cumul -= var[3];
            var[0] += var[4];
        }
        xmax[var[1] - polygon->ymin] = var[0];
        if (empty[var[1] - polygon->ymin]){
            xmin[var[1] - polygon->ymin] = var[0];
            empty[var[1] - polygon->ymin] = 0;
        }
    }
}

static void set_line_dx(polygon_t *polygon, void *ptr[], int var[6])
{
    char *empty = (char*)ptr[2];
    int *xmin = (int*)ptr[1];
    int *xmax = (int*)ptr[0];
    int cumul;
    int i;

    i = 0;
    cumul = var[2] >> 1;
    while (++i < var[2]){
        var[0] += var[4];
        cumul += var[3];
        if (cumul > var[2]){
            cumul -= var[2];
            var[1] += var[5];
        }
        xmax[var[1] - polygon->ymin] = var[0];
        if (empty[var[1] - polygon->ymin]){
            xmin[var[1] - polygon->ymin] = var[0];
            empty[var[1] - polygon->ymin] = 0;
        }
    }
}

static void polygon_init_var(polygon_t *polygon, int var[6], int i)
{
    var[0] = polygon->x[i];
    var[1] = polygon->y[i];
    var[2] = polygon->x[(i + 1) % polygon->nb_vertices] - var[0];
    var[3] = polygon->y[(i + 1) % polygon->nb_vertices] - var[1];
    var[4] = (var[2] > 0) ? 1 : -1;
    var[5] = (var[3] > 0) ? 1 : -1;
    var[2] = (var[2] > 0) ? var[2] : -var[2];
    var[3] = (var[3] > 0) ? var[3] : -var[3];
}

void get_drawline(polygon_t *polygon, int *xmax, int *xmin, char *empty)
{
    void *ptr[]= {(void*)xmax, (void*)xmin, (void*)empty};
    int var[6];
    int i;

    i = -1;
    while (++i < polygon->nb_vertices){
        polygon_init_var(polygon, var, i);
        xmax[var[1] - polygon->ymin] = var[0];
        if (empty[var[1] - polygon->ymin]){
            xmin[var[1] - polygon->ymin] = var[0];
            empty[var[1] - polygon->ymin] = 0;
        }
        if (var[2] > var[3])
            set_line_dx(polygon, ptr, var);
        else
            set_line_dy(polygon, ptr, var);
    }
}
