import re
from datetime import datetime, timedelta
from dateutil.tz import tzutc


def _list_log_files_with_filter(client, resource_group_name, server_name, filename_contains=None,
                                file_last_written=None, max_file_size=None):
    """List all the log files of a given server.

    :param resource_group_name: The name of the resource group that
    contains the resource. You can obtain this value from the Azure
    Resource Manager API or the portal.
    :type resource_group_name: str
    :param server_name: The name of the server.
    :type server_name: str
    :param filename_contains: The pattern that file name should match.
    :type filename_contains: str
    :param file_last_written: Interger in hours to indicate file last modify time,
    default value is 72.
    :type file_last_written: int
    :param max_file_size: The file size limitation to filter files.
    :type max_file_size: int
    """

    # list all files
    all_files = client.list_by_server(resource_group_name, server_name)
    files = []

    if file_last_written is None:
        file_last_written = 72
    time_line = datetime.utcnow().replace(tzinfo=tzutc()) - timedelta(hours=file_last_written)

    for f in all_files:
        if f.last_modified_time < time_line:
            continue
        if filename_contains is not None and re.search(filename_contains, f.name) is None:
            continue
        if max_file_size is not None and f.size_in_kb > max_file_size:
            continue

        del f.created_time
        files.append(f)

    return files