# Channer front-end

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


def _format_cfg(config: dict):
    # NOTE: we' assuming that  the config is _not_ malformed here
    return {
        'user': config['DATABASE_USER'], 
        'password': config['DATABASE_PASS'],
        'host': config['DATABASE_HOST'], 
        'database': config['DATABASE_NAME'],
        'port': config['DATABASE_PORT']
    }


def remove_old(config: dict, limit: int):
    config = _format_cfg(config)
    count_query = 'DELETE FROM messages WHERE time < ?'
    # TODO: don't remove pinned items

    max_age = int(time()) - (limit * 24 * 3600)
    query = ('DELETE FROM messages WHERE time < %s')
    params = (max_age,)

    conn = sql.connect(**config)
    cursor = conn.cursor(prepared=True)

    cursor.execute(count_query, params)
    conn.commit()

    cursor.close()
    conn.close()
    return 0



def message_timeout():
    pass

def read_config(path: str) -> dict:
    pairs = {}
    with open(path, 'r') as cfg:
        # Line format key=value
        for line in cfg:
            if line.startswith('#'):
                continue
            line = line.strip()
            key = line[:line.find('=')]
            value = line[line.find('=')+1:]
            pairs[key] = value

    if 'DATABASE_PORT' not in pairs:
        raise KeyError('DATABASE_PORT missing from `.env` file')
    else:
        pairs['DATABASE_PORT'] = int(pairs['DATABASE_PORT'])

    assert('DATABASE_URL' in pairs)
    assert('DATABASE_NAME' in pairs)
    assert('DATABASE_PASS' in pairs)
    assert('DATABASE_USER' in pairs)
    assert('DATABASE_HOST' in pairs)
    assert('DATABASE_PORT' in pairs)

    return pairs
            


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('-m', '--max-age-days', 
                        help='Sets the value of how old messages are allowed to be (in days)', 
                        type=int, 
                        default=7, 
                        required=False)

    parser.add_argument('-f', '---file-env', type=str, required=True)

    args = vars(parser.parse_args())

    timeout = args['max_age_days']
    config = read_config(args['file_env'])

    exit(remove_old(config, timeout))

