#include <stdio.h>
#include <stdlib.h>
#include <graph.h>
#include <math.h>
#include "graph_sup.h"

struct vec2_ {
    double x;
    double y;
};

typedef struct vec2_ vec2;

vec2 VRotate(vec2 vec, double theta) {
    vec2 new_vec = {0, 0};
    theta = theta / 180 * M_PI;
    new_vec.x = cos(theta) * vec.x - sin(theta) * vec.y;
    new_vec.y = sin(theta) * vec.x + cos(theta) * vec.y;
    return new_vec;
}

vec2 MakeFractal(vec2 pos, int n, double size, double theta, double a) {
    if (n > 1) {
        SetColor(0, 0, 255);
        //RemplirRectangle(pos.x - 5, pos.y - 5, 10, 10);
        vec2 vect1 = MakeFractal(pos, n-1, size / sqrt(2), theta + 45, a);
        vec2 offset = {-size * sqrt(2), 0};
        offset = VRotate(offset, theta - 45);
        pos.x += offset.x;
        pos.y += offset.y;
        vec2 vect2 = MakeFractal(pos, n-1, -size / sqrt(2), theta - 45 + a, a);
    } else {
        vec2 vec = {size, size};
        vec = VRotate(vec, theta + 90);
        SetColor(0, 0, 0);
        DessinerSegment(pos.x, pos.y, pos.x + vec.x, pos.y + vec.y);
        SetColor(255, 0, 0);
        //RemplirRectangle(pos.x + vec.x - 6, pos.y + vec.y - 6, 12, 12);
        return vec;
    }
}

int main(void) {
    int level;
    /*printf("Niveau de complexité : ");
    scanf("%d", &level);*/
    level = 12;

    vec2 vec = {WIDTH/2, 200};
    double a = 0;
    InitialiserGraphique();
    CreerFenetre(100, 100, WIDTH, HEIGHT);
    SetColor(255, 0, 0);
    //DessinerRectangle(vec.x-300, vec.y, 300, 300);
    while (1) {
        if (DrawNextFrame()) {
            a += 2.5;
            SetColor(255, 255, 255);
            RemplirRectangle(0, 0, WIDTH, HEIGHT);
            SetColor(0, 0, 0);
            MakeFractal(vec, level, 200, 0, a);
        }
    }
    
    Touche();
    FermerGraphique();
}