use std::io::{self, Read};

use anyhow::bail;

use crate::proto::{CliResponse, DockerCredential};
use super::{
    CliCredential,
    CliRequest,
    GlobalArgs
};


pub fn docker_store(global_args: GlobalArgs) -> anyhow::Result<()> {
    let input: DockerCredential = serde_json::from_reader(io::stdin())?;

    let req = CliRequest::SaveCredential {
        name: input.username.clone(),
        is_default: false, // is_default doesn't really mean anything for Docker credentials
        credential: CliCredential::Docker(input),
    };

    match super::make_request(global_args.server_addr, &req)?? {
        CliResponse::Empty => Ok(()),
        r => bail!("Unexpected response from server: {r}"),
    }
}


pub fn docker_get(global_args: GlobalArgs) -> anyhow::Result<()> {
    let mut server_url = String::new();
    io::stdin().read_to_string(&mut server_url)?;
    let req = CliRequest::GetDockerCredential {
       server_url: server_url.trim().to_owned()
    };

    match super::make_request(global_args.server_addr, &req)?? {
        CliResponse::Credential(CliCredential::Docker(d)) => {
            println!("{}", serde_json::to_string(&d)?);
        },
        r => bail!("Unexpected response from server: {r}"),
    }
    Ok(())
}
