use async_trait::async_trait;
use derive_new::new;
use serde::Serialize;

use crate::{
    data::{Id, Version},
    interpret::{Interpret, InterpretError, InterpretName, InterpretStatus, Outcome},
    inventory::Inventory,
    score::Score,
    topology::{HttpServer, Topology, Url},
};

#[derive(Debug, new, Clone, Serialize)]
pub struct HttpScore {
    files_to_serve: Url,
}

impl<T: Topology + HttpServer> Score<T> for HttpScore {
    fn create_interpret(&self) -> Box<dyn Interpret<T>> {
        Box::new(HttpInterpret::new(self.clone()))
    }

    fn name(&self) -> String {
        "HttpScore".to_string()
    }
}

#[derive(Debug, new, Clone)]
pub struct HttpInterpret {
    score: HttpScore,
}

#[async_trait]
impl<T: Topology + HttpServer> Interpret<T> for HttpInterpret {
    async fn execute(
        &self,
        _inventory: &Inventory,
        http_server: &T,
    ) -> Result<Outcome, InterpretError> {
        http_server.ensure_initialized().await?;
        // http_server.set_ip(topology.router.get_gateway()).await?;
        http_server.serve_files(&self.score.files_to_serve).await?;
        http_server.commit_config().await?;
        http_server.reload_restart().await?;
        Ok(Outcome::success(format!(
            "Http Server running and serving files from {}",
            self.score.files_to_serve
        )))
    }

    fn get_name(&self) -> InterpretName {
        InterpretName::Http
    }

    fn get_version(&self) -> Version {
        todo!()
    }

    fn get_status(&self) -> InterpretStatus {
        todo!()
    }

    fn get_children(&self) -> Vec<Id> {
        todo!()
    }
}
