import pyarrow


def split_arrow_table_result(axis, result, num_partitions, num_splits, metadata):
    """
    Split ``pyarrow.Table`` according to the passed parameters.

    Parameters
    ----------
    axis : {0, 1}
        The axis to perform the function along.
    result : pyarrow.Table
        Resulting table to split.
    num_partitions : int
        Number of partitions that `result` was constructed from.
    num_splits : int
        The number of splits to return.
    metadata : dict
        Dictionary with ``pyarrow.Table`` metadata.

    Returns
    -------
    list
        List of PyArrow Tables.
    """
    chunksize = (
        num_splits // num_partitions
        if num_splits % num_partitions == 0
        else num_splits // num_partitions + 1
    )
    if axis == 0:
        return [
            pyarrow.Table.from_batches([part]) for part in result.to_batches(chunksize)
        ]
    else:
        return [
            result.drop(
                [
                    result.columns[i].name
                    for i in range(result.num_columns)
                    if i >= n * chunksize or i < (n - 1) * chunksize
                ]
            )
            .append_column(result.columns[-1])
            .replace_schema_metadata(metadata=metadata)
            for n in range(1, num_splits)
        ] + [
            result.drop(
                [
                    result.columns[i].name
                    for i in range(result.num_columns)
                    if i < (num_splits - 1) * chunksize
                ]
            ).replace_schema_metadata(metadata=metadata)
        ]