#!/usr/bin/env python
# This source file is part of Soundcloud-syncer.
#
# Soundcloud-syncer 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.
#
# Soundcloud-syncer 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
# Soundcloud-syncer. If not, see <http://www.gnu.org/licenses/gpl-3.0.html>.

import argparse
import os.path

from ssyncer.sclient import sclient
from ssyncer.suser import suser
from ssyncer.serror import serror


def downloader(tgetter, output, process_tag, convert_file, max_retry, *args):
    """ Download tracks. Return number of tracks downloaded. """
    try:
        tracks = tgetter(*args)
    except serror as e:
        print(e)
        return False

    for strack in tracks:
        if strack.get("kind") != 'track':
            splaylist = strack
            out = "Processing playlist {0}!".format(splaylist.get("permalink"))
            print("\n" + "="*len(out) + "\n" + out + "\n" + "="*len(out) + "\n")
            downloader(splaylist.get_tracks, output, process_tag, convert_file, max_retry, *args)
            splaylist.write_playlist_file(output)
        else:
            try:
                if strack.download(output, max_retry) is False:
                    continue

                strack.download_artwork(output, max_retry)
                if convert_file:
                    strack.convert()
                if process_tag:
                    strack.process_tags()

            except serror as e:
                print(e)

    return len(tracks)


def main():
    parser = argparse.ArgumentParser(description="Soundcloud Syncer")
    parser.add_argument("-u", "--user", help="Soundcloud user to sync",
                        type=str, required=True)
    parser.add_argument("-c", "--client-id", help="Your client id",
                        type=str)
    parser.add_argument("-o", "--output-dir", help="Output directory",
                        type=str, required=True)
    parser.add_argument("-O", "--offset", help="Tracks offset",
                        type=int, default=0)
    parser.add_argument("-L", "--limit",
                        help="Tracks limit (default: 50, max: 200)",
                        type=int, default=50)
    parser.add_argument("-r", "--recursive",
                        help="Recursive download",
                        action="store_true")
    parser.add_argument("-t", "--tracks",
                        help="Download user's tracks instead user's likes",
                        action="store_true")
    parser.add_argument("-p", "--playlists",
                        help="Download user's playlists instead user's likes",
                        action="store_true")
    parser.add_argument("-w", "--without-tag",
                        help="Download track without tags support",
                        action="store_true")
    parser.add_argument("-C", "--convert",
                        help="Auto convert musics in mpeg format",
                        action="store_true")
    parser.add_argument("-R", "--max-retry",
                        help="Max retry for download failures (default: 3)",
                        type=int, default=3)

    args = parser.parse_args()
    process_tag = False if args.without_tag else True

    if not os.path.exists(args.output_dir):
        print(serror("Error: output directory `%s` doesn's exists." %
                     args.output_dir))
        exit(1)

    if args.limit > 200:
        print(serror("Error: tracks limit limited to 200 tracks.."))
        exit(2)

    try:
        client = sclient(args.client_id)
        user = suser(args.user, client=client)
    except serror as e:
        print(e)
        exit(3)

    tracks_getter = user.get_likes
    if args.tracks:
        tracks_getter = user.get_tracks
    elif args.playlists:
        tracks_getter = user.get_playlists

    if args.recursive:
        offset = args.offset
        while True:
            nb = downloader(
                tracks_getter,
                args.output_dir,
                process_tag,
                args.convert,
                args.max_retry,
                offset,
                args.limit)
            if nb == 0:
                break

            offset = offset + args.limit
    else:
        downloader(
            tracks_getter,
            args.output_dir,
            process_tag,
            args.convert,
            args.max_retry,
            args.offset,
            args.limit)

if __name__ == '__main__':
    main()
