firestore-cli 0.3.0

fsq, a command line client for Google Firestore: a SQL REPL with tables, query plans and index statements, and a scripting mode with JSON output
//! A field `a` adds to a document: the prompt for its name, then the list of types, which leads to
//! the edit that gives the field its value.

use super::editor::{LineEditor, ScalarKind, ValueEditor};
use super::external::ExternalDraft;
use super::state::{EditorChoice, Movement};
use super::tree::{FieldParent, MaskPath, NodePath};
use super::write::{Change, Draft, Edit};
use crate::errors::{FsqError, InvalidFieldName};
use crate::field_path::FieldPath;
use crate::render::{type_name, View};
use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
use firestore::gcloud_sdk::google::firestore::v1::{ArrayValue, MapValue, Value};
use firestore::gcloud_sdk::google::r#type::LatLng;
use firestore::gcloud_sdk::prost_types::{NullValue, Timestamp};
use firestore::FirestoreDocument;
use std::fmt::{Display, Formatter};

/// A field being added to a document, from the prompt for its name until its type is picked.
#[derive(Debug)]
pub struct NewField {
    /// The document as read when `a` was pressed, which the edit of the value starts from.
    document: FirestoreDocument,
    parent: FieldParent,
    step: NewFieldStep,
}

#[derive(Debug)]
pub enum NewFieldStep {
    /// The prompt for the name, with why the name was refused when it was last submitted.
    Naming {
        line: LineEditor,
        error: Option<FsqError>,
    },
    /// The list of types of the field at `path`, with the cursor on `selected`.
    Typing { path: MaskPath, selected: FieldType },
}

impl NewField {
    /// A field among the fields of `parent` in `document`, waiting for its name.
    pub fn new(document: &FirestoreDocument, parent: FieldParent) -> Self {
        Self {
            document: document.clone(),
            parent,
            step: NewFieldStep::Naming {
                line: LineEditor::from(""),
                error: None,
            },
        }
    }

    pub fn parent(&self) -> &FieldParent {
        &self.parent
    }

    pub fn step(&self) -> &NewFieldStep {
        &self.step
    }

    pub fn name_line_mut(&mut self) -> Option<&mut LineEditor> {
        match &mut self.step {
            NewFieldStep::Naming { line, .. } => Some(line),
            NewFieldStep::Typing { .. } => None,
        }
    }

    /// Why the name was refused when it was last submitted, an [`FsqError::InvalidFieldName`].
    pub fn error(&self) -> Option<&FsqError> {
        match &self.step {
            NewFieldStep::Naming { error, .. } => error.as_ref(),
            NewFieldStep::Typing { .. } => None,
        }
    }

    /// Goes on to the list of types with the name typed. A name that is empty, or that a field
    /// among the same fields has, stays in the prompt, and its error says why until the next
    /// submit.
    pub fn submit_name(&mut self) {
        let NewFieldStep::Naming { line, error } = &mut self.step else {
            return;
        };
        let name = line.text();
        let path = self.parent.field(name);
        let refused = if name.is_empty() {
            InvalidFieldName::Empty
        } else if NodePath::from(&path).value_in(&self.document).is_some() {
            InvalidFieldName::Taken {
                field: FieldPath::from(&path).to_string(),
            }
        } else {
            self.step = NewFieldStep::Typing {
                path,
                selected: FieldType::String,
            };
            return;
        };
        *error = Some(FsqError::InvalidFieldName(refused));
    }

    pub fn move_type(&mut self, movement: Movement) {
        if let NewFieldStep::Typing { selected, .. } = &mut self.step {
            let position = FieldType::ALL
                .iter()
                .position(|listed| listed == selected)
                .expect("the list holds every type");
            *selected = FieldType::ALL[movement.applied_to(position, FieldType::ALL.len())];
        }
    }

    /// The edit that gives the field a value of the type picked: the value editor with no text
    /// for a scalar, the external editor on an empty hex dump for bytes, and for a null, an empty
    /// map and an empty array the confirmation of the value. `None` while the name is typed.
    pub fn edit(&self, view: &View<'_>) -> Option<Edit> {
        let NewFieldStep::Typing { path, selected } = &self.step else {
            return None;
        };
        let kind = match selected {
            FieldType::String => ScalarKind::String,
            FieldType::Integer => ScalarKind::Integer,
            FieldType::Double => ScalarKind::Double,
            FieldType::Boolean => ScalarKind::Boolean,
            FieldType::Timestamp => ScalarKind::Timestamp,
            FieldType::Reference => ScalarKind::Reference {
                documents_path: view.documents_path.to_string(),
            },
            FieldType::GeoPoint => ScalarKind::GeoPoint,
            FieldType::Bytes => {
                let empty = selected.empty_value();
                let draft = ExternalDraft::field(path.clone(), &empty, EditorChoice::Fitting, view);
                return Some(Edit::editing(&self.document, Draft::External(draft)));
            }
            FieldType::Null | FieldType::Map | FieldType::Array => {
                let change = Change::Field {
                    path: path.clone(),
                    value: Some(selected.empty_value()),
                };
                return Some(Edit::confirming(&self.document, change));
            }
        };
        let editor = ValueEditor::empty(path.clone(), kind);
        Some(Edit::editing(&self.document, Draft::Value(editor)))
    }
}

/// The types `a` offers a new field, in the order of its list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FieldType {
    String,
    Integer,
    Double,
    Boolean,
    Timestamp,
    Null,
    Map,
    Array,
    Reference,
    GeoPoint,
    Bytes,
}

impl FieldType {
    pub const ALL: [Self; 11] = [
        Self::String,
        Self::Integer,
        Self::Double,
        Self::Boolean,
        Self::Timestamp,
        Self::Null,
        Self::Map,
        Self::Array,
        Self::Reference,
        Self::GeoPoint,
        Self::Bytes,
    ];

    /// A value of this type that holds nothing: empty, zero, false or the epoch. A new null, map,
    /// array or bytes field starts from it.
    fn empty_value(self) -> Value {
        let value_type = match self {
            Self::String => ValueType::StringValue(String::new()),
            Self::Integer => ValueType::IntegerValue(0),
            Self::Double => ValueType::DoubleValue(0.0),
            Self::Boolean => ValueType::BooleanValue(false),
            Self::Timestamp => ValueType::TimestampValue(Timestamp::default()),
            Self::Null => ValueType::NullValue(NullValue::NullValue.into()),
            Self::Map => ValueType::MapValue(MapValue::default()),
            Self::Array => ValueType::ArrayValue(ArrayValue::default()),
            Self::Reference => ValueType::ReferenceValue(String::new()),
            Self::GeoPoint => ValueType::GeoPointValue(LatLng::default()),
            Self::Bytes => ValueType::BytesValue(Vec::new()),
        };
        Value {
            value_type: Some(value_type),
        }
    }
}

impl Display for FieldType {
    /// The type as the type column of the tree names it.
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.write_str(type_name(&self.empty_value()))
    }
}