use std::{any::Any, sync::Arc};

use async_trait::async_trait;

use datafusion::{
    arrow::{
        array::{Array, ArrayRef, StringBuilder},
        datatypes::{DataType, Field, Schema, SchemaRef},
        record_batch::RecordBatch,
    },
    datasource::{datasource::TableProviderFilterPushDown, TableProvider, TableType},
    error::DataFusionError,
    logical_plan::Expr,
    physical_plan::{memory::MemoryExec, ExecutionPlan},
};

struct PgCatalogViewsBuilder {
    schemaname: StringBuilder,
    viewname: StringBuilder,
    viewowner: StringBuilder,
    definition: StringBuilder,
}

impl PgCatalogViewsBuilder {
    fn new(capacity: usize) -> Self {
        Self {
            schemaname: StringBuilder::new(capacity),
            viewname: StringBuilder::new(capacity),
            viewowner: StringBuilder::new(capacity),
            definition: StringBuilder::new(capacity),
        }
    }

    fn finish(mut self) -> Vec<Arc<dyn Array>> {
        let columns: Vec<Arc<dyn Array>> = vec![
            Arc::new(self.schemaname.finish()),
            Arc::new(self.viewname.finish()),
            Arc::new(self.viewowner.finish()),
            Arc::new(self.definition.finish()),
        ];

        columns
    }
}

pub struct PgCatalogViewsProvider {
    data: Arc<Vec<ArrayRef>>,
}

// https://www.postgresql.org/docs/14/view-pg-views.html
impl PgCatalogViewsProvider {
    pub fn new() -> Self {
        let builder = PgCatalogViewsBuilder::new(0);

        Self {
            data: Arc::new(builder.finish()),
        }
    }
}

#[async_trait]
impl TableProvider for PgCatalogViewsProvider {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn table_type(&self) -> TableType {
        TableType::View
    }

    fn schema(&self) -> SchemaRef {
        Arc::new(Schema::new(vec![
            Field::new("schemaname", DataType::Utf8, false),
            Field::new("viewname", DataType::Utf8, false),
            Field::new("viewowner", DataType::Utf8, true),
            Field::new("definition", DataType::Utf8, true),
        ]))
    }

    async fn scan(
        &self,
        projection: &Option<Vec<usize>>,
        _filters: &[Expr],
        _limit: Option<usize>,
    ) -> Result<Arc<dyn ExecutionPlan>, DataFusionError> {
        let batch = RecordBatch::try_new(self.schema(), self.data.to_vec())?;

        Ok(Arc::new(MemoryExec::try_new(
            &[vec![batch]],
            self.schema(),
            projection.clone(),
        )?))
    }

    fn supports_filter_pushdown(
        &self,
        _filter: &Expr,
    ) -> Result<TableProviderFilterPushDown, DataFusionError> {
        Ok(TableProviderFilterPushDown::Unsupported)
    }
}
