#!python
"""
yt2mp3
A program that simplifies the process of searching, downloading and
converting Youtube videos to MP3 files with embedded metadata via the
iTunes API.
bin/yt2mp3
Brett Stevenson (c) 2018
"""

import sys, logging
from collections import defaultdict
from colorama import init, Fore, Style
from yt2mp3 import util, opts
from yt2mp3.song import Song

def main(args):
  # Initialize colorama for Windows
  init()
  args = opts.parse_options(args)
  # Set logging level
  logging.basicConfig(level=logging.WARNING if args.quiet else logging.INFO, format='%(message)s')
  queue = list()
  data = defaultdict(str)
  try:
    if args.playlist:
      url = 'https://www.youtube.com/playlist?list='+args.playlist.split('list=')[-1]
      if not util.validate_url(url, bool(args.playlist)):
        logging.warning(Fore.RED+'✘ '+Style.RESET_ALL+'Unable to validate the provided URL')
        sys.exit()
      queue = util.get_video_list(url)
    elif args.url:
      data['video_url'] = args.url
      if len(data['video_url']) == 11:
        data['video_url'] = 'https://www.youtube.com/watch?v='+data['video_url']
      if not util.validate_url(data['video_url']):
        logging.warning(Fore.RED+'✘ '+Style.RESET_ALL+'Unable to validate the provided URL')
        sys.exit()
    else:
      # Get song track/artist from user
      if args.track or args.artist:
        data['track_name'] = ' '.join(args.track)
        data['artist_name'] = ' '.join(args.artist)
      else:
        data['track_name'] = input(' Track: ')
        data['artist_name'] = input(' Artist: ')
        if args.collection:
          data['collection_name'] = input(' Album: ')
    if not args.playlist:
      queue.append(data['video_url'])
    for i,url in enumerate(queue):
      if args.playlist:
        title = util.get_video_title(url)
        logging.info('%s of %s: %s', (i+1), len(queue), title)
        data['video_url'] = url
      song = Song(util.get_song_data(data, args.collection))
      if not args.overwrite and song.file_exists():
        logging.warning(Fore.RED+'✘ '+Style.RESET_ALL+'This song already exists in the output directory')
        if args.playlist:
          continue
        sys.exit()
      video = song.download(args.verbose)
      path = song.convert_to_mp3(video)
      song.set_id3(path, args.resolution)
  # Catch program exit and `ctrl+c` to clean-up temporary files
  except (KeyboardInterrupt, SystemExit):
    util.cleanup()
    logging.info('\n'+Fore.RED+'✘ '+Style.RESET_ALL+'Cancelled')
    sys.exit()
  util.cleanup()
  logging.info(Fore.GREEN+'✔ '+Style.RESET_ALL+'Done')


if __name__ == '__main__':
  main(sys.argv[1:])
