from pathlib import Path
import json
import sqlite3


def transfer_data(db_dir, ss_dir, skips=None):
    """Transfers data existing from files in `ss_dir` to `db_dir`.

    `ss_dir` contains the legacy `server_settings` JSON files.

    `db_dir` contains the sqlite3 db files.

    Args:
        db_dir (str): the location of the database files
        ss_dir (str): the location of the existing server settings files
        skips (list, optional): a list of invalid databases to skip;
            defaults to None

    Returns:
        list: containing file names of files that produced errors

    """
    errs = []

    for db in db_dir.glob('*.db'):
        ss = Path(f"""{db.name.rstrip('.db')}.json""")
        if skips and db in skips:
            continue
        if not ss.exists():
            print(f'Server settings {ss.name} doesn\'t exist. Skipping...')
            errs.append(ss)
            continue

        try:
            with open(ss, 'r') as f:
                ssjson = json.load(f)
        except json.JSONDecodeError as e:
            print(f'Couldn\'t read JSON {ss.name}!', e)
            errs.append(ss)
            continue

        conn = sqlite3.connect(db)
        cursor = conn.cursor()

        # Add users back to their assigned roles
        for role, user in ssjson['users'].items():
            # Don't add back super-authorized; let the bot handle this
            if role == 's-authorized':
                continue
            for _u in user:
                cursor.execute(
                    'insert into roles values(?, ?)',
                    (role, _u)
                    )

        conn.commit()

        # Add groups back to their assigned roles
        for role, group in ssjson['group'].items():
            if role == 's-authorized':
                continue
            for _g in group:
                cursor.execute(
                    'insert into roles values(?, ?)',
                    (role, _g)
                    )

        conn.commit()

        # Add only groups back to boss role
        for role, group in ssjson['role'].items():
            for _g in group:
                # In the old server settings, an '@' indicated a user mention
                if '@' in _g:
                    continue
                cursor.execute(
                    'insert into roles values(?, ?)',
                    (role, _g)
                    )

        conn.commit()

        # Add channels
        for ch_type, channels in ssjson['channel'].items():
            if ch_type == 'management':
                ch_type = 'settings'
            for channel in channels:
                cursor.execute(
                    'insert into channels values(?, ?)',
                    (ch_type, channel)
                    )

        conn.commit()

        # Add contribution points to guild
        for user, points in ssjson['talt'].items():
            if type(points) is not int:
                points = int(points)*20
            if user == 'guild':
                cursor.execute(
                    'insert into guild values(?, ?)',
                    (ssjson['guild_level'], points)
                    )
            elif user == 'remainder':
                cursor.execute(
                    'insert into contribution values(?, ?)',
                    ('0', points)
                    )
            else:
                cursor.execute(
                    'insert into contribution values(?,?)',
                    (user, points)
                    )

        conn.commit()
        conn.close()

    return errs