/*
This program is for simulating orbits of planets around a star.
A body can be a star, planet or moon. (Doesn't matter for now)
 */

use orbital_simulation::run;

// Gravitational constant
static G: f64 = 6.67430e-11;

struct Body {
    name: String,
    mass: f64,
    radius: f64,
}

fn calculate_gravitational_force(body1: &Body, body2: &Body, distance: f64) -> f64 {
    (G * body1.mass * body2.mass) / distance.powi(2)
}

fn calculate_required_velocity(body1: &Body, body2: &Body, distance: f64, force: f64) -> f64 {
    (force * distance / body2.mass).sqrt()
}

fn main() {
    // simulate a two body system to simplify the problem
    let sun = Body {
        name: "Sun".to_string(),
        mass: 1.989e30,
        radius: 6.9634e8,
    };

    let earth = Body {
        name: "Earth".to_string(),
        mass: 5.972e24,
        radius: 6.371e6,
    };

    /*// Calculate the velocity pulling the earth towards the sun
    let distance = 1.496e11;
    let force = calculate_gravitational_force(&sun, &earth, distance);

    let velocity = calculate_required_velocity(&sun, &earth, distance, force);

    println!("The velocity of the earth is: {} m/s", velocity);*/

    // Now we simulate a whole orbit around the sun
    let distance = 1.496e11;
    let force = calculate_gravitational_force(&sun, &earth, distance);
    let velocity = calculate_required_velocity(&sun, &earth, distance, force);

    let mut time = 0.0;
    let mut position = 0.0;
    let mut velocity = velocity;
    let mut acceleration = 0.0;
    let mut force = force;
    let mut distance = distance;
    let mut mass = earth.mass;
    let mut radius = earth.radius;

    let dt = 1.0;
    let steps = 1000;

    for _ in 0..steps {
        // Calculate the acceleration
        acceleration = force / mass;

        // Calculate the new position
        position += velocity * dt + 0.5 * acceleration * dt.powi(2);

        // Calculate the new velocity
        velocity += acceleration * dt;

        // Calculate the new distance
        distance = position;

        // Calculate the new force
        force = calculate_gravitational_force(&sun, &earth, distance);

        // Calculate the new mass
        mass = earth.mass;

        // Calculate the new radius
        radius = earth.radius;

        // Calculate the new time
        time += dt;

        println!("Time: {} s, Position: {} m, Velocity: {} m/s, Acceleration: {} m/s^2, Force: {} N, Distance: {} m, Mass: {} kg, Radius: {} m", time, position, velocity, acceleration, force, distance, mass, radius);
    }

    pollster::block_on(run());
}
