# MusicDB,  a music manager with web-bases UI that focus on music.
# Copyright (C) 2017-2021  Ralf Stemmer <ralf.stemmer@gmx.net>
# 
# 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/>.
"""
Introduction to the mise-CLI-module

Example:

    To run a search from command-line, execute this module using ``musicdb``:

    .. code-block:: bash

        # Find anything matching to Rammstein:
        musicdb mise Rammstein

        # get the ID for Rammsteins song Rammstein:
        musicdb mise -t song -f id Rammstein
        # -t/--target can be all(default), artist, album, song
        # -f/--format can be short(default), id

"""

import argparse
from musicdb.lib.modapi     import MDBModule
from musicdb.lib.db.musicdb import MusicDatabase
from musicdb.mdbapi.mise    import MusicDBMicroSearchEngine
import logging


class mise(MDBModule, MusicDBMicroSearchEngine):

    def __init__(self, config, database):
        MDBModule.__init__(self)
        MusicDBMicroSearchEngine.__init__(self, config)

        self.database = database


    @staticmethod
    def MDBM_CreateArgumentParser(parserset, modulename):
        parser = parserset.add_parser(modulename, help="Micro Search Engine to search throug the artists, albums and songs in the music-database")
        parser.set_defaults(module=modulename)
        parser.add_argument("-t", "--target"
            , action="store"
            , type=str
            , choices=["all","artist","album","song"]
            , default="all"
            , help="select target table that will be displayed")
        parser.add_argument("-f", "--format"
            , action="store"
            , type=str
            , choices=["short","id"]
            , default="short"
            , help="select the format that shall be used to display the infos. Default is \"short\"")
        parser.add_argument("searchstring", help="string that will be search in a list of artists, albums and songs")
    

    def PrintResults_Short(self, target, results):
        """ A method to generate a short output for search-results of a specific target 

        Args:
            target (str): Target that was searched for, and that is covered by the results.
                It can be ``all``, ``artist``, ``album`` and ``songs``

            results (list): A list of search-results generated by lib.pymise.MusicDBMicroSearchEngine

        Returns:
            *nothing*
        """

        if target == "all" or target == "artist":
            print("\033[1;37m          Artists          \033[0m")
            print("\033[1;46m P \033[1;41m   ID  \033[1;46m Name \033[0m")
            for result in results[0]:
                artist = self.database.GetArtistById(result[0])
                formatstring = "\033[0;36m{:3d} \033[0;31m{:5d}  \033[1;36m{}\033[0m"
                print(formatstring.format(result[1], artist["id"], artist["name"]))

        if target == "all" or target == "album":
            print("\033[1;37m          Albums           \033[0m")
            print("\033[1;46m P \033[1;41m   ID  \033[1;44m Origin \033[1;44m Songs \033[1;46m Release - Name \033[0m")
            for result in results[1]:
                album = self.database.GetAlbumById(result[0])
                formatstring  = "\033[0;36m{:3d} \033[0;31m{:5d}"   # prob, ID
                formatstring += " \033[1;34m{:8s}"                  # origin
                formatstring += "   \033[1;34m{:3d}"                # numofsongs
                formatstring += "  \033[1;36m{:4d}\033[1;34m -"     # release
                formatstring += " \033[1;36m{}"                     # name
                formatstring += "\033[0m" 
                print(formatstring.format(result[1], album["id"], 
                    album["origin"],
                    album["numofsongs"],
                    album["release"],
                    album["name"]))

        if target == "all" or target == "songs":
            print("\033[1;37m          Songs            \033[0m")
            print("\033[1;46m P \033[1;41m   ID  \033[1;44m CD/Number \033[1;46m Name \033[0m")
            for result in results[2]:
                song = self.database.GetSongById(result[0])
                formatstring  = "\033[0;36m{:3d} \033[0;31m{:5d}"   # prob, ID
                formatstring += "   \033[1;34m{:1d}\033[0;34m-"     # cd
                formatstring += "\033[1;34m{:2d}"                   # number
                formatstring += "      \033[1;36m{}"                # name
                formatstring += "\033[0m" 
                print(formatstring.format(result[1], song["id"], 
                    song["cd"],
                    song["number"],
                    song["name"]))


    def PrintResults_ID(self, target, results):
        """ A method to generate a short output for search-results of a specific target 

        Same as :func:`~mise.mise.PrintResults_Short` without any details

        Args:
            target (str): Target that was searched for, and that is covered by the results.
                It can be ``all``, ``artist``, ``album`` and ``songs``

            results (list): A list of search-results generated by lib.pymise.MusicDBMicroSearchEngine

        Returns:
            *nothing*
        """
        if not self.database:
            return

        if target == "all" or target == "artist":
            print("\033[1;37m          Artists          \033[0m")
            print("\033[1;46m P \033[1;41m   ID  \033[1;44m Name \033[0m")
            for result in results[0]:
                artist = self.database.GetArtistById(result[0])
                formatstring = "\033[0;36m{:3d} \033[0;31m{:5d}  \033[1;34m{}\033[0m"
                print(formatstring.format(result[1], artist["id"], artist["name"]))

        if target == "all" or target == "album":
            print("\033[1;37m          Albums           \033[0m")
            print("\033[1;46m P \033[1;41m   ID  \033[1;44m Name \033[0m")
            for result in results[1]:
                album = self.database.GetAlbumById(result[0])
                formatstring = "\033[0;36m{:3d} \033[0;31m{:5d}  \033[1;34m{}\033[0m"
                print(formatstring.format(result[1], album["id"], album["name"]))

        if target == "all" or target == "songs":
            print("\033[1;37m          Songs            \033[0m")
            print("\033[1;46m P \033[1;41m   ID  \033[1;44m Name \033[0m")
            for result in results[2]:
                song = self.database.GetSongById(result[0])
                formatstring = "\033[0;36m{:3d} \033[0;31m{:5d}  \033[1;34m{}\033[0m"
                print(formatstring.format(result[1], song["id"], song["name"]))


    # return exit-code
    def MDBM_Main(self, args):

        logging.debug("Initialize MiSE cache…")
        self.UpdateCache()
        logging.debug("Searching…")
        results = self.Find(args.searchstring)

        logging.debug("Printing results…")
        if args.format == "short":
            self.PrintResults_Short(args.target, results)
        elif args.format == "id":
            self.PrintResults_ID(args.target, results)

        return 0



# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4

