#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import syd
import click
from sqlalchemy import exc
from box import Box

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


@click.command(context_settings=CONTEXT_SETTINGS)
@click.option('--clear', is_flag=True, help='Remove all views (DANGEROUS)')
@click.option('--default', is_flag=True, help='Insert all default views')
@click.option('--db', default='',
              help='DB filename (SYD_DB_FILENAME environment variable is used if no filename)')
@syd.add_options(syd.common_options)
def syd_clear_view(db, clear, default, **kwargs):
    """
    Remove all views and/or insert default ones
    """

    # open the db
    db_filename = syd.get_db_filename(db)
    db = syd.open_db(db_filename)

    # check arg
    if not clear and not default:
        print('Doing nothing. Use --clear and/or --default')

    # delete the table FormatView and all the views
    if clear:
        if 'FormatView' in db.tables:
            s = f'Drop table FormatView;'
            db.query(s)
            syd.log.info(f"Removing the table FormatView")
        s = f"SELECT name FROM sqlite_master WHERE type = 'view';"
        res = db.query(s)
        for r in res:
            s = f"DROP view {r['name']}"
            syd.log.info(f"Removing view {r['name']}")
            db.query(s)
        # set the FormatView table
        syd.create_format_view_table(db)

    # re-create all default views
    if default:
        syd.insert_default_views(db)

# -----------------------------------------------------------------------------
if __name__ == '__main__':
    syd_clear_view()
