mod util;
mod endpoints;
mod models;

use rocket::{routes};
use util::constants;
use util::debug;


pub fn connect() -> redis::RedisResult<()> {
    let client = redis::Client::open("redis://127.0.0.1:7878/")?;
    let mut connector = client.get_connection()?;
    // let mut connector = client.get_connection();
    // connector.set("Name", "Redis");
    // println!("DB name:: {}", connector.get("Name"));

    match client.get_connection()  {
        Ok(mut connector) => {
            util::colored_text::print_colored_text_info("[DB] Connected ");

            Ok(())
        },
        Err(e) => {
            util::colored_text::print_colored_text_err("[DB] Error, check redis database is running? (./Database/run.sh) Fix REDIS_PORT if not correctly setted;\n[Wiki] Instructions: https://git.sociocyber.site:5000/SocioCybereeng/Hydroponic_systems/src/branch/master/ResourceHub/Readme.md ", e.to_string());
            Err(e)
        }
    }
}

 #[rocket::main]
 async fn main() -> Result<(), rocket::Error> {
    util::colored_text::print_colored_text_brand("> SocioCybereeng ");
    util::colored_text::print_colored_text_project("> Project: Hydroponic Systems ");
    util::colored_text::print_colored_text_info("- [Welcome to ResourceHUB API] ");
    
    if util::constants::IS_DEBUG == true {
        debug::print_debug_info();
    }


     // let DBconnector = ;
    
    // Attempt to connect to DB and check the result
    let conection = connect();
    match conection {
    // match DBconnector::connect() {

        Ok(conection) => {
            // If the connection is successful, store it or use it as needed
            let mut _db = conection;


            // Start server
            let _rocket = rocket::build()
                .mount(format!("/api/v{}/", constants::API_VERSION), routes![
                    endpoints::sensors::data::create,
                    endpoints::sensors::data::get,
                    endpoints::sensors::data::get_by_id,
                ])
                .launch()
                .await?;

            Ok(())
        },
        Err(err) => {
            // Handle connection error and stop execution
            std::process::exit(1);
        }
    }
    
 }
