import logging
from logging import Logger

from libbot.utils import config_get, config_set, config_delete
from mongodb_migrations.base import BaseMigration

logger: Logger = logging.getLogger(__name__)


class Migration(BaseMigration):
    def upgrade(self):
        try:
            # Categories
            config_set(
                "custom_channels",
                config_get("customchannels", "categories"),
                "categories",
            )
            config_delete("customchannels", "categories")

            # User defaults
            config_delete(
                "user",
                "defaults",
            )
        except Exception as exc:
            logger.error(
                "Could not upgrade the config during migration '%s' due to: %s",
                __name__,
                exc,
            )

        self.db.users.update_many(
            {"customchannel": {"$exists": True}},
            {"$rename": {"customchannel": "custom_channel"}},
        )
        self.db.users.update_many(
            {"customrole": {"$exists": True}},
            {"$rename": {"customrole": "custom_role"}},
        )

    def downgrade(self):
        try:
            # Categories
            config_set(
                "customchannels",
                config_get("custom_channels", "categories"),
                "categories",
            )
            config_delete("custom_channels", "categories")

            # User defaults
            config_set(
                "customrole",
                None,
                "defaults",
                "user",
            )
            config_set(
                "customchannel",
                None,
                "defaults",
                "user",
            )
        except Exception as exc:
            logger.error(
                "Could not downgrade the config during migration '%s' due to: %s",
                __name__,
                exc,
            )

        self.db.users.update_many(
            {"custom_channel": {"$exists": True}},
            {"$rename": {"custom_channel": "customchannel"}},
        )
        self.db.users.update_many(
            {"custom_role": {"$exists": True}},
            {"$rename": {"custom_role": "customrole"}},
        )