#!/usr/bin/python
# Copyright (c) 2014-2018 Cedric Bellegarde <cedric.bellegarde@adishatz.org>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import sys
# Make sure we'll find the pygobject module, even in JHBuild
sys.path.insert(1, '/usr/lib/python3.6')
# Make sure we'll find the lollypop modules, even in JHBuild
sys.path.insert(1, '/usr/lib/python3.6/site-packages')
import gi
gi.require_version('Secret', '1')
gi.require_version('TotemPlParser', '1.0')
gi.require_version('GstPbutils', '1.0')
gi.require_version('Gtk', '3.0')
gi.require_version('Gst', '1.0')
from gi.repository import Gtk, Gst, GLib

from lollypop.database_albums import AlbumsDatabase
from lollypop.database_tracks import TracksDatabase
from lollypop.database_artists import ArtistsDatabase
from lollypop.database_genres import GenresDatabase
from lollypop.database import Database
from lollypop.sqlcursor import SqlCursor
from lollypop.tagreader import TagReader
from lollypop.settings import Settings
from lollypop.define import Type
from lollypop.playlists import Playlists

import xml.etree.ElementTree as etree
import os
import sqlite3
from time import time
import sys


class Application(Gtk.Application):
    """
        Lollypop cli application
        We need this as Lollypop class
        depends on the global object: Gio.Application.get_default()
    """

    def __init__(self):
        """
            Create application
        """
        Gtk.Application.__init__(
                            self,
                            application_id='org.gnome.Lollypop')
        Gst.init(None)
        self.cursors = {}
        self.settings = Settings.new()
        self.albums = AlbumsDatabase()
        self.artists = ArtistsDatabase()
        self.genres = GenresDatabase()
        self.tracks = TracksDatabase()
        self.playlists = Playlists()
        self.db = Database()
        SqlCursor.add(self.db)

    def usage(self):
        """
            Show usage
        """
        print("usage: lollypop-cli export-playlists")
        print("Export playlists to m3u format in current directory")
        print("")
        print("usage: lollypop-cli import-rhythmbox")
        print("Import Rhythmbox stats")

    def import_rhythmbox(self):
        """
            Import rhythmbox stats
        """
        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':
                uri = child.find('location').text
                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(uri, last, count)
                    sql.execute("UPDATE tracks set ltime=?, popularity=? WHERE uri=?", (last, count, uri))

        sql.commit()
        sql.close()

    def export_playlists(self):
        """
            Export playlists to m3u format
        """
        for (playlist_id, name) in self.playlists.get():
            f = open("%s.m3u" % name, 'w')
            f.write("#EXTM3U\n")
            for uri in self.playlists.get_tracks(playlist_id):
                f.write(uri+'\n')
            f.close()


if __name__ == '__main__':

    app = Application()
    larg = len(sys.argv)
    if larg == 1:
        app.usage()
        exit(0)
    if sys.argv[1] == "youtube" and larg == 6:
        app.add_youtube(sys.argv)
    elif sys.argv[1] == "import-rhythmbox":
        app.rhythmbox()
    elif sys.argv[1] == "export-playlists":
        app.export_playlists()
    else:
        app.usage()
