from openpyxl.styles import Alignment


def prepare_excel(workbook, filters=True):
    """
    Formats the excel a bit in order to be displayed nicely

        workbook: openpyxl workbook
        filters: If True enable excel filtering headers
        returns: formated workbook
    """
    # openpyxl is an extra requirement

    for worksheet in workbook:
        # estimate column width
        for col in worksheet.columns:
            max_length = 0
            column = col[0].column_letter
            for cell in col:
                if len(str(cell.value)) > max_length:
                    max_length = len(str(cell.value))
            adjusted_width = (max_length + 3) * 1.2
            worksheet.column_dimensions[column].width = min([adjusted_width, 50])

            # enable excel filters
            if filters is True:
                worksheet.auto_filter.ref = f"A1:{column}1"

        # enable word wrap
        for row in worksheet.iter_rows():
            for cell in row:
                cell.alignment = Alignment(wrap_text=True)
                if isinstance(cell.value, str):
                    cell.value = cell.value.strip()
                    if cell.value.isdigit():
                        cell.value = int(cell.value)

    return workbook