use std::{
    fmt::Display,
    io,
};

struct Fahrenheit(f64);
struct Celsius(f64);

enum Convert {
    FahrenheitToCelsius(Fahrenheit),
    CelsiusToFahrenheit(Celsius),
}

impl Display for Convert {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Convert::FahrenheitToCelsius(fahrenheit) => {
                write!(f, "{fahrenheit} is equal to {}", Celsius::from(fahrenheit))
            }
            Convert::CelsiusToFahrenheit(celsius) => {
                write!(f, "{celsius} is equal to {}", Fahrenheit::from(celsius))
            }
        }
    }
}

const RED: &str = "\x1b[0;31m";
const YELLOW: &str = "\x1b[0;33m";
const BLUE: &str = "\x1b[0;34m";
const RESET: &str = "\x1b[0m";
fn main() {
    println!("Welcome to the temperature converter!");

    loop {
        println!("Which way do you need to convert?");
        println!("{BLUE}Fahrenheit{RESET} {YELLOW}--->{RESET} {RED}Celsius: Press 1{RESET}");
        println!("{RED}Celsius{RESET} {YELLOW}--->{RESET} {BLUE}Fahrenheit: Press 2{RESET}");
        println!("(Press q to quit)");

        let mut direction = String::new();
        io::stdin()
            .read_line(&mut direction)
            .expect("Failed to read line.");

        let direction = direction.trim();

        let result = match direction {
            "q" | "Q" => break,
            "1" => Convert::FahrenheitToCelsius(Fahrenheit(read_temp())),
            "2" => Convert::CelsiusToFahrenheit(Celsius(read_temp())),
            _ => {
                println!("Please make a valid selection!");
                continue;
            }
        };

        println!("{result}")
    }
}

fn read_temp() -> f64 {
    println!("What is starting temperature?");
    let mut temp = String::new();
    io::stdin()
        .read_line(&mut temp)
        .expect("Failed to read line.");
    let parsed_temp: f64 = temp.trim().parse().expect("Please type a number!");
    parsed_temp
}

impl From<&Fahrenheit> for Celsius {
    fn from(fahrenheit: &Fahrenheit) -> Self {
        Celsius((fahrenheit.0 - 32.0) * 0.555555556)
    }
}

impl Display for Celsius {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}C", self.0)
    }
}

impl From<&Celsius> for Fahrenheit {
    fn from(celsius: &Celsius) -> Self {
        Fahrenheit((celsius.0 * 1.8) + 32.0)
    }
}

impl Display for Fahrenheit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}F", self.0)
    }
}
