use crate::{
    models::SharedAppState,
    modules::evok::{
        models::{command::SetCommand, devices::relay::RelayPostData},
        types::EvokSender,
    },
};
use actix_web::{
    get, post,
    web::{Data, Json},
    HttpResponse,
};

// Every request handler in this file is prefixed with '/evok'
// -------------------------------
// ------------ /evok ------------
// -------------------------------

/// Get evok's current state
#[get("/state")]
pub async fn get_evok_state(data: Data<SharedAppState>) -> HttpResponse {
    HttpResponse::Ok().json(data.lock().unwrap().evok_state.clone())
}

/// Set unipi relay to desired value
#[post("/relay")]
pub async fn set_relay(body: Json<RelayPostData>, evok_tx: Data<EvokSender>) -> HttpResponse {
    let data = match serde_json::to_string(&body.data) {
        Ok(val) => val,
        Err(e) => return HttpResponse::BadRequest().body(e.to_string()),
    };

    let cmd = SetCommand::new(
        "relay".to_string(),
        body.circuit.clone(),
        data.trim_end_matches(|c| c == '}')
            .trim_start_matches(|c| c == '{')
            .to_string(),
    );
    // TODO -> remove to_string() and as_bytes() and use directly the vec
    // curently it's not possible because wrong serialization (cmd: Set (it cant be uppercase))
    match evok_tx.send(cmd.to_string().as_bytes().to_vec()).await {
        Ok(_) => HttpResponse::Ok().body("Relay successfully set"),
        Err(me) => HttpResponse::BadRequest().body(me.0),
    }
}
