use super::column_data::expect_type;
use chrono_tz::Tz;
use std::{io::Write, sync::Arc};

use either::Either;

use crate::{
    binary::{read_vec, Encoder, ReadEx},
    errors::{DriverError, Error, Result},
    types::{
        column::{
            array::ArrayColumnData, column_data::LowCardinalityAccessor, list::List,
            nullable::NullableColumnData, ArcColumnWrapper, ColumnWrapper, StringPool,
        },
        Column, ColumnType, FromSql, SqlType, Value, ValueRef,
    },
};

use super::{
    column_data::{BoxColumnData, ColumnData},
    ColumnFrom,
};

pub(crate) struct StringColumnData {
    pool: StringPool,
}

pub(crate) struct StringAdapter<K: ColumnType> {
    pub(crate) column: Column<K>,
}

impl StringColumnData {
    pub(crate) fn with_capacity(capacity: usize) -> Self {
        Self {
            pool: StringPool::with_capacity(capacity),
        }
    }

    pub(crate) fn load<T: ReadEx>(reader: &mut T, size: usize) -> Result<Self> {
        if reader.string_size_stream() {
            return Self::load_with_size_stream(reader, size);
        }
        // Each string after its length, into one buffer grown as they come.
        let mut chunk = Vec::new();
        let mut ends = Vec::with_capacity(size.min(1 << 20));
        for _ in 0..size {
            reader.read_str_onto(&mut chunk)?;
            ends.push(chunk.len() as u64);
        }
        Ok(Self {
            pool: pool_from(chunk, &ends)?,
        })
    }

    /// Where each row ends, counted from the first one, then the bytes of
    /// all the rows (`SerializationString::serializeBinaryBulkWithSizeStream`
    /// over the network): one buffer of their exact length.
    fn load_with_size_stream<T: ReadEx>(reader: &mut T, size: usize) -> Result<Self> {
        // Grown as the offsets arrive past a million rows: the count is the
        // server's word.
        let mut ends = Vec::with_capacity(size.min(1 << 20));
        let mut last = 0_u64;
        for _ in 0..size {
            let end: u64 = reader.read_scalar()?;
            if end < last {
                return Err(Error::Driver(DriverError::Deserialize(
                    format!("string offsets go back from {last} to {end}").into(),
                )));
            }
            ends.push(end);
            last = end;
        }
        let total = usize::try_from(last).map_err(|_| Error::Driver(DriverError::Overflow))?;
        let chunk = read_vec(reader, total)?;
        Ok(Self {
            pool: pool_from(chunk, &ends)?,
        })
    }
}

fn pool_from(chunk: Vec<u8>, ends: &[u64]) -> Result<StringPool> {
    StringPool::from_chunk(chunk, ends).ok_or_else(|| {
        Error::Driver(DriverError::Deserialize(
            "string offsets past their bytes".into(),
        ))
    })
}

/// Writes `rows` strings in the layout `encoder` is set to: each after its
/// length, or where each ends and then all their bytes. Each string is
/// taken once and let go of when written: the table of ends is reserved
/// first and filled in behind the bytes.
fn save_strings<I, S>(encoder: &mut Encoder, rows: usize, strings: I)
where
    I: Iterator<Item = S>,
    S: AsRef<[u8]>,
{
    if !encoder.string_size_stream() {
        for s in strings {
            encoder.byte_string(s);
        }
        return;
    }
    let buffer = encoder.buffer_mut();
    let table = buffer.len();
    buffer.resize(table + rows * 8, 0);
    let mut end = 0_u64;
    for (row, s) in strings.take(rows).enumerate() {
        let bytes = s.as_ref();
        end += bytes.len() as u64;
        buffer.extend_from_slice(bytes);
        let slot = table + row * 8;
        buffer[slot..slot + 8].copy_from_slice(&end.to_le_bytes());
    }
}

impl ColumnFrom for Vec<String> {
    fn column_from<W: ColumnWrapper>(data: Self) -> W::Wrapper {
        W::wrap(StringColumnData { pool: data.into() })
    }
}

impl ColumnFrom for Vec<&str> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        W::wrap(StringColumnData {
            pool: source.into(),
        })
    }
}

impl ColumnFrom for Vec<&[u8]> {
    fn column_from<W: ColumnWrapper>(data: Self) -> W::Wrapper {
        W::wrap(StringColumnData { pool: data.into() })
    }
}

trait StringSource {
    fn into_value(self) -> Value;
}

impl StringSource for String {
    fn into_value(self) -> Value {
        self.into()
    }
}

impl StringSource for &str {
    fn into_value(self) -> Value {
        self.into()
    }
}

impl StringSource for Vec<u8> {
    fn into_value(self) -> Value {
        Value::String(Arc::new(self))
    }
}

impl ColumnFrom for Vec<Vec<String>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> <W as ColumnWrapper>::Wrapper {
        make_array_of_array::<W, String>(source)
    }
}

impl ColumnFrom for Vec<Vec<&str>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> <W as ColumnWrapper>::Wrapper {
        make_array_of_array::<W, &str>(source)
    }
}

fn make_array_of_array<W: ColumnWrapper, S: StringSource>(
    source: Vec<Vec<S>>,
) -> <W as ColumnWrapper>::Wrapper {
    let fake: Vec<String> = Vec::with_capacity(source.len());
    let inner = ColumnFrom::column_from::<ArcColumnWrapper>(fake);
    let sql_type = inner.sql_type();

    let mut data = ArrayColumnData {
        inner,
        offsets: List::with_capacity(source.len()),
    };

    for vs in source {
        let mut inner = Vec::with_capacity(vs.len());
        for v in vs {
            let value: Value = v.into_value();
            inner.push(value)
        }
        data.push(Value::Array(sql_type.clone().into(), Arc::new(inner)));
    }

    W::wrap(data)
}

impl ColumnFrom for Vec<Option<Vec<u8>>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        make_opt_column::<W, Vec<u8>>(source)
    }
}

impl ColumnFrom for Vec<Option<&str>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        make_opt_column::<W, &str>(source)
    }
}

impl ColumnFrom for Vec<Option<String>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        make_opt_column::<W, String>(source)
    }
}

fn make_opt_column<W: ColumnWrapper, S: StringSource>(source: Vec<Option<S>>) -> W::Wrapper {
    let inner = Arc::new(StringColumnData::with_capacity(source.len()));

    let mut data = NullableColumnData {
        inner,
        nulls: Vec::with_capacity(source.len()),
    };

    for value in source {
        let item = if let Some(v) = value {
            let inner = v.into_value();
            Value::Nullable(Either::Right(Box::new(inner)))
        } else {
            Value::Nullable(Either::Left(SqlType::String.into()))
        };
        data.push(item);
    }

    W::wrap(data)
}

impl LowCardinalityAccessor for StringColumnData {
    fn get_string(&self, index: usize) -> &[u8] {
        self.pool.get(index)
    }
}

impl ColumnData for StringColumnData {
    fn sql_type(&self) -> SqlType {
        SqlType::String
    }

    fn save(&self, encoder: &mut Encoder, start: usize, end: usize) {
        // By index: a range far into the column costs only its own length.
        save_strings(
            encoder,
            end - start,
            (start..end).map(|index| self.pool.get(index)),
        );
    }

    fn len(&self) -> usize {
        self.pool.len()
    }

    fn push(&mut self, value: Value) {
        let s: Vec<u8> = value.into();
        let mut b = self.pool.allocate(s.len());
        b.write_all(s.as_ref()).unwrap();
    }

    fn at(&self, index: usize) -> ValueRef<'_> {
        let s = self.pool.get(index);
        ValueRef::from(s)
    }

    fn clone_instance(&self) -> BoxColumnData {
        Box::new(Self {
            pool: self.pool.clone(),
        })
    }

    unsafe fn get_internal(
        &self,
        pointers: &[*mut *const u8],
        level: u8,
        _props: u32,
        expected: &SqlType,
    ) -> Result<()> {
        expect_type(self.sql_type(), expected)?;
        assert_eq!(level, 0);
        *pointers[0] = &self.pool as *const StringPool as *const u8;
        *(pointers[1] as *mut usize) = self.len();
        Ok(())
    }

    fn get_timezone(&self) -> Option<Tz> {
        None
    }

    fn get_low_cardinality_accessor(&self) -> Option<&dyn LowCardinalityAccessor> {
        Some(self)
    }
}

impl<K: ColumnType> ColumnData for StringAdapter<K> {
    fn sql_type(&self) -> SqlType {
        SqlType::String
    }

    fn save(&self, encoder: &mut Encoder, start: usize, end: usize) {
        let value = |index| -> Vec<u8> { Vec::from_sql(self.column.at(index)).unwrap() };
        save_strings(encoder, end - start, (start..end).map(value));
    }

    fn len(&self) -> usize {
        self.column.len()
    }

    fn push(&mut self, _value: Value) {
        unimplemented!()
    }

    fn at(&self, index: usize) -> ValueRef<'_> {
        self.column.at(index)
    }

    fn clone_instance(&self) -> BoxColumnData {
        unimplemented!()
    }

    fn get_timezone(&self) -> Option<Tz> {
        None
    }
}

#[cfg(test)]
mod test {
    use std::io::Cursor;

    use super::*;
    use crate::binary::ColumnReader;

    fn texts(column: &StringColumnData) -> Vec<&[u8]> {
        (0..column.len()).map(|row| column.pool.get(row)).collect()
    }

    #[test]
    fn test_strings_with_a_size_stream() {
        let column = StringColumnData {
            pool: vec!["a", "", "bcd"].into(),
        };

        // Each string after its length.
        let mut encoder = Encoder::new();
        column.save(&mut encoder, 0, 3);
        assert_eq!(encoder.get_buffer(), b"\x01a\x00\x03bcd");

        // Where each one ends, then all the bytes.
        let mut encoder = Encoder::new();
        encoder.set_string_size_stream(true);
        column.save(&mut encoder, 0, 3);
        let bytes = encoder.get_buffer();
        let mut expected = Encoder::new();
        for end in [1_u64, 1, 4] {
            expected.write(end);
        }
        expected.write_bytes(b"abcd");
        assert_eq!(bytes, expected.get_buffer());

        let mut cursor = Cursor::new(&bytes[..]);
        let loaded = StringColumnData::load(&mut ColumnReader::new(&mut cursor, true), 3).unwrap();
        assert_eq!(texts(&loaded), [&b"a"[..], b"", b"bcd"]);
        assert_eq!(cursor.position() as usize, bytes.len());

        // A range counts from its first row.
        let mut encoder = Encoder::new();
        encoder.set_string_size_stream(true);
        column.save(&mut encoder, 1, 3);
        let mut expected = Encoder::new();
        expected.write(0_u64);
        expected.write(3_u64);
        expected.write_bytes(b"bcd");
        assert_eq!(encoder.get_buffer(), expected.get_buffer());

        // Offsets that go back are an error, and bytes not there yet wait.
        let mut encoder = Encoder::new();
        encoder.write(2_u64);
        encoder.write(1_u64);
        let bytes = encoder.get_buffer();
        let mut cursor = Cursor::new(&bytes[..]);
        let err = StringColumnData::load(&mut ColumnReader::new(&mut cursor, true), 2)
            .err()
            .expect("offsets that go back");
        assert!(err.to_string().contains("go back"), "{err}");
        let mut encoder = Encoder::new();
        encoder.write(5_u64);
        encoder.write_bytes(b"abc");
        let bytes = encoder.get_buffer();
        let mut cursor = Cursor::new(&bytes[..]);
        let err = StringColumnData::load(&mut ColumnReader::new(&mut cursor, true), 1)
            .err()
            .expect("missing bytes");
        assert!(err.is_would_block(), "{err}");
    }
}