#!/usr/bin/env python
#
# Script to manage renaming existing files in given directory and
# propagating that change to database. Typical usage: renaming files
# from 'title.mp3' to title - artist.mp3'
#
# Actions:
#
# - record all filenames and inode numbers
# - external: rename the files
# - update records with new filenames for each inode number
# - update external database with new paths

import os
import sqlite3

PHASE = 2

# Check file of same name exists in parent directory
source_dir = '/home/kae/tmp/Singles'   # os.getcwd()
db = "/home/kae/tmp/singles.sqlite"


def main():
    with sqlite3.connect(db) as connection:
        cursor = connection.cursor()
        if PHASE == 1:
            cursor.execute(
                "CREATE TABLE IF NOT EXISTS mp3s "
                "(inode INTEGER, oldname TEXT, newname TEXT)"
            )

            for fname in os.listdir(source_dir):
                fullpath = os.path.join(source_dir, fname)
                inode = os.stat(fullpath).st_ino
                sql = f'INSERT INTO mp3s VALUES ({inode}, "{fname}", "")'
                cursor.execute(sql)

        if PHASE == 2:
            for fname in os.listdir(source_dir):
                fullpath = os.path.join(source_dir, fname)
                inode = os.stat(fullpath).st_ino
                sql = (
                    f'UPDATE mp3s SET newname = "{fname}" WHERE inode={inode}'
                )
                try:
                    cursor.execute(sql)
                except sqlite3.OperationalError:
                    print(f"Error with {inode} -> {fname}")

        cursor.close()


main()
