#!/usr/bin/python3

from gi.repository import GLib

import xml.etree.ElementTree as etree
import os
import sqlite3

LOCAL_PATH = os.path.expanduser("~") + "/.local/share/lollypop"
DB_PATH = "%s/lollypop.db" % LOCAL_PATH
RB_DB_PATH = os.path.expanduser("~") + "/.local/share/rhythmbox/rhythmdb.xml"

sql = sqlite3.connect(DB_PATH, 600.0)

tree = etree.parse(RB_DB_PATH)
root = tree.getroot()
for child in root:
    if child.attrib['type'] == 'song':
        filepath = GLib.filename_from_uri(child.find('location').text)[0]
        try:
            last = child.find('last-played').text
        except:
            last = None
        try:
            count = child.find('play-count').text
        except:
            count = None
        if count is not None and last is not None:
            print(filepath, last, count)
            sql.execute("UPDATE tracks set ltime=?, popularity=? WHERE filepath=?", (last, count, filepath))

sql.commit()
sql.close()
