#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 2017-04-24 Friedrich Weber <friedrich.weber@netknights.it>
#
# Copyright (c) 2017, Friedrich Weber
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from this
# software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

from edumfa.lib.usercache import create_filter, get_cache_time
from edumfa.models import UserCache, db

__doc__ = """
This script deletes expired entries from the user cache.
"""
__version__ = "0.1"

import click
from flask.cli import FlaskGroup

from edumfa.app import create_app
from edumfa.lib.usercache import create_filter, get_cache_time
from edumfa.models import UserCache, db

CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])


def create_prod_app():
    return create_app("production", silent=True, script=True)


@click.group(
    cls=FlaskGroup,
    add_default_commands=False,
    create_app=create_prod_app,
    context_settings=CONTEXT_SETTINGS,
    epilog="Check out our docs at https://edumfa.readthedocs.io/ for more details",
)
def cli():
    pass


def _get_expired_entries():
    """
    Returns a list of all cache entries that are considered expired.
    """
    filter_condition = create_filter(expired=True)
    return (
        UserCache.query.filter(filter_condition)
        .order_by(UserCache.timestamp.desc())
        .all()
    )


@cli.command()
@click.option(
    "--noaction", is_flag=True, help="List expired cache entries without deleting them."
)
def delete(noaction):
    """
    Delete all cache entries that are considered expired according to the
    UserCacheExpiration configuration setting.
    If the user cache is disabled, no entries are deleted.
    If '--noaction' is passed, expired cache entries are listed, but not
    actually deleted.
    """
    if not get_cache_time():
        print("User cache is disabled, not doing anything.")
    else:
        print("Expired entries:")
        entries = _get_expired_entries()
        if entries:
            print(
                "{:<5} {:<10} {:<10} {:<30} {:<10}".format(
                    "id", "username", "resolver", "timestamp", "user id"
                )
            )
        for entry in entries:
            print(
                "{:<5} {:<10} {:<10} {:<30} {:<10}".format(
                    entry.id,
                    entry.username,
                    entry.resolver,
                    entry.timestamp.isoformat(),
                    entry.user_id,
                )
            )
        print("{} entries".format(len(entries)))
        if not noaction:
            for entry in entries:
                print("Deleting entry with id={} ...".format(entry.id))
                entry.delete()
            print("Deleted {} expired entries.".format(len(entries)))
            db.session.commit()
        else:
            print("'--noaction' was passed, not doing anything.")


if __name__ == "__main__":
    cli()
