/// Adapted from https://github.com/jorgecarleitao/arrow2/blob/main/src/compute/sort/primitive/sort.rs
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
use arrow::{
    array::{Array, ArrowPrimitiveType, NullBufferBuilder, PrimitiveArray},
    buffer::{Buffer, NullBuffer, ScalarBuffer},
    compute::SortOptions,
    datatypes::ArrowNativeType,
};

/// # Safety
/// `indices[i] < values.len()` for all i
#[inline]
fn k_element_sort_inner<T, F>(values: &mut [T], descending: bool, limit: usize, mut cmp: F)
where
    T: ArrowNativeType,
    F: FnMut(&T, &T) -> std::cmp::Ordering,
{
    if descending {
        let (before, _, _) = values.select_nth_unstable_by(limit, |x, y| cmp(y, x));
        before.sort_unstable_by(|x, y| cmp(x, y));
    } else {
        let (before, _, _) = values.select_nth_unstable_by(limit, |x, y| cmp(x, y));
        before.sort_unstable_by(|x, y| cmp(x, y));
    }
}

fn sort_values<T, F>(values: &mut [T], mut cmp: F, descending: bool, limit: usize)
where
    T: ArrowNativeType,
    F: FnMut(&T, &T) -> std::cmp::Ordering,
{
    if limit != values.len() {
        return k_element_sort_inner(values, descending, limit, cmp);
    }

    if descending {
        values.sort_unstable_by(|x, y| cmp(y, x));
    } else {
        values.sort_unstable_by(cmp);
    }
}

fn sort_nullable<T, F>(
    values: &[T],
    nulls: &NullBuffer,
    cmp: F,
    options: &SortOptions,
    limit: usize,
) -> (Buffer, Option<NullBuffer>)
where
    T: ArrowNativeType,
    F: FnMut(&T, &T) -> std::cmp::Ordering,
{
    assert!(limit <= values.len());
    if options.nulls_first && limit < nulls.null_count() {
        let buffer = vec![T::default(); limit];
        let bitmap = NullBuffer::new_null(limit);
        return (buffer.into(), Some(bitmap));
    }

    let mut buffer = Vec::<T>::with_capacity(values.len());
    let mut new_nulls = NullBufferBuilder::new(values.len());
    let slices = nulls.valid_slices();

    if options.nulls_first {
        // validity is [0,0,0,...,1,1,1,1]
        new_nulls.append_n_nulls(nulls.null_count());
        new_nulls.append_n_non_nulls(values.len() - nulls.null_count());
        new_nulls.truncate(limit);

        // extend buffer with constants followed by non-null values
        buffer.resize(nulls.null_count(), T::default());
        for (start, end) in slices {
            buffer.extend_from_slice(&values[start..end]);
        }

        // sort values
        sort_values(
            &mut buffer.as_mut_slice()[nulls.null_count()..],
            cmp,
            options.descending,
            limit - nulls.null_count(),
        );
    } else {
        // validity is [1,1,1,...,0,0,0,0]
        new_nulls.append_n_non_nulls(values.len() - nulls.null_count());
        new_nulls.append_n_nulls(nulls.null_count());
        new_nulls.truncate(limit);

        // extend buffer with non-null values
        for (start, end) in slices {
            buffer.extend_from_slice(&values[start..end]);
        }

        // sort all non-null values
        sort_values(
            buffer.as_mut_slice(),
            cmp,
            options.descending,
            limit - nulls.null_count(),
        );

        if limit > values.len() - nulls.null_count() {
            // extend remaining with nulls
            buffer.resize(buffer.len() + nulls.null_count(), T::default());
        }
    }
    // values are sorted, we can now truncate the remaining.
    buffer.truncate(limit);
    buffer.shrink_to_fit();

    (buffer.into(), new_nulls.finish())
}

/// Sorts a [`PrimitiveArray`] according to `cmp` comparator and [`SortOptions`].
pub fn sort_by<T, F>(
    array: &PrimitiveArray<T>,
    cmp: F,
    options: &SortOptions,
    limit: Option<usize>,
) -> PrimitiveArray<T>
where
    T: ArrowPrimitiveType,
    F: FnMut(&T::Native, &T::Native) -> std::cmp::Ordering,
{
    let limit = limit.unwrap_or_else(|| array.len());
    let limit = limit.min(array.len());

    let values = array.values().inner().typed_data::<T::Native>();
    let nulls = array.nulls();

    let (buffer, nulls) = if let Some(nulls) = nulls {
        sort_nullable(values, nulls, cmp, options, limit)
    } else {
        let mut buffer = Vec::<T::Native>::new();
        buffer.extend_from_slice(values);

        sort_values(buffer.as_mut_slice(), cmp, options.descending, limit);
        buffer.truncate(limit);
        buffer.shrink_to_fit();

        (buffer.into(), None)
    };

    PrimitiveArray::<T>::new(ScalarBuffer::new(buffer, 0, limit), nulls)
}

#[cfg(test)]
mod tests {
    use arrow::{
        array::{ArrowPrimitiveType, PrimitiveArray},
        compute::SortOptions,
        datatypes::Int8Type,
    };

    use super::sort_by;

    fn test_sort_primitive_arrays<T>(
        data: Vec<Option<T::Native>>,
        options: SortOptions,
        expected_data: Vec<Option<T::Native>>,
    ) where
        T: ArrowPrimitiveType,
        T::Native: Ord,
    {
        let input = {
            let mut builder = PrimitiveArray::<T>::builder(data.len());
            builder.extend(data.into_iter());
            builder.finish()
        };
        let expected = {
            let mut builder = PrimitiveArray::<T>::builder(expected_data.len());
            builder.extend(expected_data.clone().into_iter());
            builder.finish()
        };
        let output = sort_by(&input, |l, r| l.cmp(r), &options, None);
        assert_eq!(expected, output);

        // with limit
        let limit = 3;
        let expected = {
            let mut builder = PrimitiveArray::<T>::builder(limit);
            builder.extend(expected_data.into_iter().take(limit));
            builder.finish()
        };
        let output = sort_by(&input, |l, r| l.cmp(r), &options, Some(limit));
        assert_eq!(expected, output);
    }

    #[test]
    fn ascending_nulls_first() {
        test_sort_primitive_arrays::<Int8Type>(
            vec![None, Some(3), Some(5), Some(2), Some(3), None],
            SortOptions {
                descending: false,
                nulls_first: true,
            },
            vec![None, None, Some(2), Some(3), Some(3), Some(5)],
        );
    }

    #[test]
    fn ascending_nulls_last() {
        test_sort_primitive_arrays::<Int8Type>(
            vec![None, Some(3), Some(5), Some(2), Some(3), None],
            SortOptions {
                descending: false,
                nulls_first: false,
            },
            vec![Some(2), Some(3), Some(3), Some(5), None, None],
        );
    }

    #[test]
    fn descending_nulls_first() {
        test_sort_primitive_arrays::<Int8Type>(
            vec![None, Some(3), Some(5), Some(2), Some(3), None],
            SortOptions {
                descending: true,
                nulls_first: true,
            },
            vec![None, None, Some(5), Some(3), Some(3), Some(2)],
        );
    }

    #[test]
    fn descending_nulls_last() {
        test_sort_primitive_arrays::<Int8Type>(
            vec![None, Some(3), Some(5), Some(2), Some(3), None],
            SortOptions {
                descending: true,
                nulls_first: false,
            },
            vec![Some(5), Some(3), Some(3), Some(2), None, None],
        );
    }
}
