#include <stdio.h>
#include <stdlib.h>
#include <graph.h>

typedef struct rekt {
    int x;
    int y;
    int w;
    int h;
} rekt;

void drawRekt(rekt rectangle) {
    DessinerRectangle(rectangle.x, rectangle.y, rectangle.w, rectangle.h);
}

int max(int x, int y) {
    return x > y ? x : y;
}

int min(int x, int y) {
    return x < y ? x : y;
}

rekt makeRekt() {
    rekt toto;
    char valid = 0;
    while(valid != 2) {
        if (SourisCliquee()) {
            SourisPosition();
            if (valid == 0) {
                toto.x = _X;
                toto.y = _Y;
                valid = 1;
            }
            else if (valid == 1) {
                toto.w = _X - toto.x;
                toto.h = _Y - toto.y;
                valid = 2;
            }
        }
    }

    if (toto.w < 0) {
        toto.w = -toto.w;
        toto.x -= toto.w;
    }

    if (toto.h < 0) {
        toto.h = -toto.h;
        toto.y -= toto.h;
    }

    return toto;
}

void translate(rekt* rectangle, int x, int y) {
    rectangle->x += x;
    rectangle->y += y;
}

void rotate(rekt* rectangle, int rotation) {
    if (rotation == 1) {
        int buffer = rectangle->w;
        rectangle->w = rectangle->h;
        rectangle->h = buffer;
        rectangle->x -= rectangle->w;
    } else if (rotation == -1) {
        int buffer = rectangle->w;
        rectangle->w = rectangle->h;
        rectangle->h = buffer;
        rectangle->y -= rectangle->h;
    }
}

rekt intersection(rekt rect1, rekt rect2) {
    rekt rect_inter;
    rect_inter.x = max(rect1.x, rect2.x);
    rect_inter.y = max(rect1.y, rect2.y);

    rect_inter.w = min(rect1.x + rect1.w, rect2.x + rect2.w);
    rect_inter.h = min(rect1.y + rect1.h, rect2.y + rect2.h);

    rect_inter.w -= rect_inter.x;
    rect_inter.h -= rect_inter.y;

    return rect_inter;
}

rekt mariage(rekt rect1, rekt rect2) {
    rekt rect_inter;
    rect_inter.x = min(rect1.x, rect2.x);
    rect_inter.y = min(rect1.y, rect2.y);

    rect_inter.w = max(rect1.x + rect1.w, rect2.x + rect2.w);
    rect_inter.h = max(rect1.y + rect1.h, rect2.y + rect2.h);

    rect_inter.w -= rect_inter.x;
    rect_inter.h -= rect_inter.y;

    return rect_inter;
}

int main(void) {
    rekt rectangle_toto1 = {300, 300, 300, 200};
    rekt rectangle_toto2 = {350, 400, 200, 250};

    InitialiserGraphique();
    CreerFenetre(100, 100, 1200, 700);
    drawRekt(rectangle_toto1);
    drawRekt(rectangle_toto2);
    ChoisirCouleurDessin(CouleurParComposante(255, 0, 0));
    drawRekt(intersection(rectangle_toto1, rectangle_toto2));
    ChoisirCouleurDessin(CouleurParComposante(0, 0, 255));
    drawRekt(mariage(rectangle_toto1, rectangle_toto2));
    Touche();
    FermerGraphique();
}