#!/usr/bin/python

'''
A simple script to get the top 100 songs from Clementine DB and copy it to
my phone.

TODO:
    1. Handle phone unmount properly. MTPFS suck!
    2. Dont copy files already there
    3. Delete old files?
    4. Remove hard links
    5. Mount with python

'''

import sqlite3
import urllib.parse as lib
import shutil

def main():

    DB = sqlite3.connect('/home/jaseem/.config/Clementine/clementine.db')
    SQL = 'select filename from songs order by rating desc limit 100'

    cursor = DB.cursor()
    data = cursor.execute(SQL).fetchall()

    log = "/home/jaseem/player-sync.log"
    # destination = "/tmp/music/"
    destination = "/home/jaseem/t/Internal storage/Music/"

    f = open(log,'w')

    for file in data:
        # Decode binary to UTF-8 string, and parse for path
        parse = lib.urlparse(file[0].decode("utf-8"))
        path = lib.unquote(parse.path)

        try:
            open(path)
            shutil.copy2(path, destination)
            f.write("[✓] " + path + '\n')

        except OSError as err:
            f.write("[✗] Unable to find phone \n")

        except IOError as err:
            f.write("[✗] " + err + path + '\n')

    f.close()

if __name__ == "__main__":
    main()
