# Channer front-end

from os import getenv
import argparse
import mysql.connector as sql

CONFIG = {
    'database': getenv('DATABASE_NAME'),
    'password': getenv('DATABASE_PASS'),
    'user': getenv('DATABASE_USER'),
    'host': getenv('DATABASE_HOST'),
    'port': int(getenv('DATABASE_PORT')),
}

def purge_clamped_messages(cursor, channels: list, limit: int):
    pass

def message_limit(limit: int):
    count_query = '''
        SELECT channel_name, COUNT(time) FROM messages
        GROUP BY channel_name;
    '''
    conn = sql.connect(**CONFIG)
    cursor = conn.cursor(prepared=True)

    cursor.execute(count_query,())
    # figure out which channels need pruning
    for i in cursor:
        print(i)

    # collect the channels that require filtering
    channels = list(filter((None).__ne__, [limit if chan[1] > limit else None for chan in cursor]))
    if len(channels) > 0:
        purge_clamped_messages(cursor, channels, limit)
    else:
        print(f'[ {__file__} ] : No messages to remove from clamped set')

    cursor.close()
    conn.close()



def message_timeout():
    pass


if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        description='A script which can be setup as a chronjob to make messaging' 
        ' similar to how image boards clean up threads'
    )

    parser.add_argument('-t', '--time-out', type=float, required=False)
    parser.add_argument('-m', '--message-limit',  type=int, required=False)


    args = vars(parser.parse_args())

    limit = args['message_limit']
    timeout = args['time_out']

    # timeout is given in days 30 => 30 day time limit
    if limit: message_limit(limit)
    if timeout: message_timeout(timeout)

