import click
from app import db
from flask import current_app
from app.models import Setting, User


def seed_defaults():
    defaults = {
        "butterbox_name": current_app.config["BUTTERBOX_NAME"],
        "butterbox_logo": current_app.config["BUTTERBOX_LOGO"],
        "ssid": current_app.config["BUTTERBOX_SSID"],
        "wifi_password": current_app.config["BUTTERBOX_WIFI_PASSWORD"],
        "enable_access_point": current_app.config["ENABLE_ACCESS_POINT"],
        "apply_changes": "false",
        "onboarding_complete": "false",
        "lock_root_password": "false",
        "enable_file_viewer": current_app.config["ENABLE_FILE_VIEWER"],
        "enable_chat": current_app.config["ENABLE_CHAT"],
        "enable_deltachat": current_app.config["ENABLE_DELTACHAT"],
        "ssh_password": "",
        "admin_password": current_app.config["ADMIN_PASSWORD"],
        "enable_wifi_sharing": current_app.config["ENABLE_WIFI_SHARING"],
        "butterbox_hostname": current_app.config["BUTTERBOX_HOSTNAME"],
        "root_account_settings": "",
        "ssh_access_settings": "disable_ssh",
        "root_password": "",
        "first_setup": "true",
    }

    for key, value in defaults.items():
        exists = Setting.query.filter_by(key=key).first()
        if not exists:
            db.session.add(Setting(key=key, value=value))
            click.echo("Created new setting {}".format(key))
        else:
            click.echo("Found existing setting {}".format(key))
    db.session.commit()

    admin_user_exists = User.query.filter_by(username='admin').first()
    if not admin_user_exists:
        u = User(username='admin')
        u.set_password('admin')
        db.session.add(u)
        db.session.commit()
        click.echo("Created new admin user")
    else:
        click.echo("Found existing admin user")


@click.command("seed-settings")
def seed_settings_command():
    """Seed default settings into the database (only if missing)."""
    seed_defaults()
    click.echo("Finished seeding default settings.")
