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

static int check_position(sfml_t *sfml, int rectangle[])
{
    if ((rectangle[0] < 0 && rectangle[2] < 0) ||
        ((rectangle[0] > sfml->width) && (rectangle[2] > sfml->width))
        || (rectangle[1] < 0 && rectangle[3] < 0)
        || ((rectangle[1] > sfml->height)
        && (rectangle[3] > sfml->height)))
        return (1);
    return (0);
}

void my_filled_rectangle(sfml_t *sfml, int rectangle[4], uint32_t color)
{
    int h_line[3];
    int var[4];
    int i;

    if (check_position(sfml, rectangle))
        return;
    i = -1;
    var[0] = (rectangle[2] < rectangle[0]) ? rectangle[2] : rectangle[0];
    var[0] = (var[0] < 0) ? 0 : var[0];
    var[1] = (rectangle[3] < rectangle[1]) ? rectangle[3] : rectangle[1];
    var[1] = (var[1] < 0) ? 0 : var[1];
    var[2] = (rectangle[2] < rectangle[0]) ? rectangle[0] : rectangle[2];
    var[2] = (var[2] > sfml->width) ? sfml->width : var[2];
    var[3] = my_abs(rectangle[3] - rectangle[1]);
    var[3] = (var[3] > sfml->height) ? sfml->height : var[3];
    while (++i < var[3]){
        h_line[0] = var[1] + i;
        h_line[1] = var[0];
        h_line[2] = var[2];
        my_horizontal_line(sfml, h_line, color);
    }
}

static void set_h_line(int h_line[3], int y, int x1, int x2)
{
    h_line[0] = y;
    h_line[1] = x1;
    h_line[2] = x2;
}

static void draw_border(sfml_t *sfml, int rect[5], uint32_t border_color)
{
    int h_line[3];
    int i;

    i = -1;
    while (++i < rect[4] - 1){
        set_h_line(h_line, rect[1] + i, rect[0], rect[2]);
        my_horizontal_line(sfml, h_line, border_color);
        set_h_line(h_line, rect[3] - i, rect[0], rect[2]);
        my_horizontal_line(sfml, h_line, border_color);
    }
    i = rect[1] + rect[4] - 2;
    while (++i <= rect[3] - rect[4] + 1){
        set_h_line(h_line, i, rect[0], rect[0] + rect[4] - 1);
        my_horizontal_line(sfml, h_line, border_color);
        set_h_line(h_line, i, rect[2] - rect[4] + 1, rect[2]);
        my_horizontal_line(sfml, h_line, border_color);
    }
}

void my_rectangle(sfml_t *sfml, int rect[5],
uint32_t border_color, uint32_t fill_color)
{
    int h_line[3];
    int i;

    if (check_position(sfml, rect))
        return;
    if (border_color & 0xff && rect[4] > 0)
        draw_border(sfml, rect, border_color);
    if (fill_color & 0xff){
        i = rect[1] + rect[4] - 1;
        while (++i <= rect[3] - rect[4]){
            set_h_line(h_line, i, rect[0] + rect[4], rect[2] - rect[4]);
            my_horizontal_line(sfml, h_line, fill_color);
        }
    }
}
