pub use sequoia_keystore_backend::PasswordSource;

use crate::Result;
use crate::keystore_protocol_capnp::keystore;

impl TryFrom<keystore::password_source::Reader<'_>> for PasswordSource {
    type Error = anyhow::Error;

    fn try_from(reader: keystore::password_source::Reader<'_>) -> Result<Self> {
        use keystore::password_source::Which;

        match reader.which()? {
            Which::Inline(()) => Ok(PasswordSource::Inline),
            Which::InlineWithConfirmation(())
                => Ok(PasswordSource::InlineWithConfirmation),
            Which::ExternalSideEffect(())
                => Ok(PasswordSource::ExternalSideEffect),
            Which::ExternalOnDemand(())
                => Ok(PasswordSource::ExternalOnDemand),
        }
    }
}

impl keystore::password_source::Builder<'_> {
    /// Serialize PasswordSource.
    pub fn set_password_source(&mut self, password_source: PasswordSource)
        -> Result<()>
    {
        match password_source {
            PasswordSource::Inline => self.set_inline(()),
            PasswordSource::InlineWithConfirmation
                => self.set_inline_with_confirmation(()),
            PasswordSource::ExternalSideEffect
                => self.set_external_side_effect(()),
            PasswordSource::ExternalOnDemand
                => self.set_external_on_demand(()),
        }

        Ok(())
    }
}
