use std::net::Ipv4Addr;

use model::{CreateStatus, Instance, SshPubkey, Subnet};

pub mod args;
pub mod config;
#[cfg(feature = "mock")]
pub mod mock;
pub mod model;
pub mod net;

pub use hickory_proto;
use net::mac::MacAddr;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub enum InstanceQuery {
    Name(String),
    MacAddr(MacAddr),
    Ipv4Addr(Ipv4Addr),
}

#[tarpc::service]
pub trait Nazrin {
    /// Creates a new instance.
    async fn new_instance(build_args: args::NewInstance) -> Result<uuid::Uuid, String>;
    /// Poll for the current status of an instance being created.
    async fn poll_new_instance(task_id: uuid::Uuid) -> Option<CreateStatus>;
    /// Deletes an existing instance.
    ///
    /// This should involve deleting all related disks and clearing
    /// the lease information from the subnet data, if any.
    async fn delete_instance(name: String) -> Result<(), String>;
    /// Gets a single instance by the given InstanceQuery.
    async fn find_instance(query: InstanceQuery) -> Result<Option<Instance>, String>;
    /// Gets a list of existing instances.
    async fn get_instances(with_status: bool) -> Result<Vec<Instance>, String>;
    /// Cleans up unusable entries in the database.
    async fn garbage_collect() -> Result<(), String>;
    /// Creates a new subnet.
    ///
    /// Unlike instances, subnets shouldn't perform any changes to the
    /// interfaces they reference. This should be used primarily for
    /// ease-of-use and bookkeeping (e.g., assigning dynamic leases).
    async fn new_subnet(build_args: Subnet) -> Result<Subnet, String>;
    /// Modifies an existing subnet.
    async fn modify_subnet(edit_args: Subnet) -> Result<Subnet, String>;
    /// Gets a list of existing subnets.
    async fn get_subnets() -> Result<Vec<Subnet>, String>;
    /// Deletes an existing subnet.
    async fn delete_subnet(interface: String) -> Result<(), String>;
    /// Gets the cloud-init user-data for the given instance.
    async fn get_instance_userdata(id: i32) -> Result<Vec<u8>, String>;
    /// Gets all SSH keys stored in the database.
    async fn get_ssh_pubkeys() -> Result<Vec<SshPubkey>, String>;
    /// Adds a new SSH public key to the database.
    async fn add_ssh_pubkey(pub_key: String) -> Result<SshPubkey, String>;
    /// Deletes an SSH public key from the database.
    async fn delete_ssh_pubkey(id: i32) -> Result<(), String>;
}

/// Create a new NazrinClient.
pub fn new_client(sock: tokio::net::UnixStream) -> NazrinClient {
    use tarpc::tokio_serde::formats::Bincode;
    use tarpc::tokio_util::codec::LengthDelimitedCodec;

    let framed_io = LengthDelimitedCodec::builder()
        .length_field_type::<u32>()
        .new_framed(sock);
    let transport = tarpc::serde_transport::new(framed_io, Bincode::default());
    NazrinClient::new(Default::default(), transport).spawn()
}

pub use tarpc::client::RpcError;
pub use tarpc::context::current as default_ctx;