#!/usr/bin/python3
# -*- python -*-
"""Migrate notification settings."""

import argparse
import logging

import gi
from gi.repository import Gio

logging.basicConfig(level=logging.INFO)


def gschema_exists(schema):
    source = Gio.SettingsSchemaSource.get_default()
    if not source:
        return False

    return source.lookup(schema, True) != None

def migrate_old_settings():
    logging.debug(f"migrating old notification settings...")
    if not gschema_exists("com.ubuntu.notifications.hub"):
        logging.debug(f"skipping settings migration: schema does not exist")
        return

    old_settings = Gio.Settings.new("com.ubuntu.notifications.hub")
    blacklist = old_settings.get_value("blacklist").unpack()
    if not blacklist:
        logging.debug(f"skipping settings migration: setting does not exist")
        return

    old_settings.reset("blacklist")

    for app in blacklist:
        app_key = "/".join([app[0] if app[0] else "dpkg", app[1]])
        settings_path = "/com/lomiri/NotificationSettings/{app_key}/"
        settings = Gio.Settings.new_with_path(
            "com.lomiri.notifications.settings", settings_path
        )
        settings.set_boolean("enable-notifications", False)
        logging.debug(f"migrating notification setting for {app_key}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("-D", "--debug",
                        help="Enable debug logging",
                        action="store_true",
                        default=False)
    args = parser.parse_args()
    if args.debug:
        logging.getLogger().setLevel(logging.DEBUG)
    migrate_old_settings()
    logging.info("Notification settings were migrated successfully")
