# coding=utf-8
from __future__ import unicode_literals
__requires__ = [
    'cherrypy_cors',
]

import youtube_dl

import vlc

import time
import os
import urllib


import cherrypy
import cherrypy_cors
cherrypy_cors.install()

from time import sleep

class Music:
    def __init__(self,path=None):
        try:
            i=vlc.Instance()
            l=i.media_list_new()
            l.insert_media(i.media_new(path),0)
            self.p=i.media_list_player_new()
            self.p.set_media_list(l)
        except Exception as e:
            raise

    def play(self):
        self.p.play()

    def stop(self):
        self.p.stop()

    def getsong(self, style):
        pass
        #TODO RAndom


    # --------------------
    # | VOLUME FUNCTIONS |
    # --------------------

    def setVolume(self, volume):
        self.p.get_media_player().audio_set_volume(self.assertVolume(volume))
        print("Volume: " + str(volume) + "\n")

    def increvementVolume(self, volume):
        player_volume = self.assertVolume( self.p.get_media_player().audio_get_volume() + volume)
        self.p.get_media_player().audio_set_volume( player_volume )
        print("Volume: " + str(player_volume) + "\n")

    def assertVolume(self, volume):
        if volume >= 170:
            return 170
        elif volume <= 0:
            return 0
        return volume

class MyLogger(object):
    def debug(self, msg):
        print(msg)

    def warning(self, msg):
        pass

    def error(self, msg):
        print(msg)

class Root(object):

    def __init__(self):
        path = "."
        self.player = Music(path)


    @cherrypy.expose
    def index(self):
        return open("index.html")

    @cherrypy.expose
    def playList(self, name=None):
        self.stopIt()
        self.player=Music(name)
        self.player.play()
        return

    @cherrypy.expose
    def stopIt(self):
        print("\n\n\n")
        try:
            self.player.stop()
        except ValueError:
            pass
        return

    @cherrypy.expose
    def addVolume(self, volume):
        try:
            self.player.increvementVolume(int(volume))
        except ValueError:
            pass
        return

    def my_hook(self, d):
        if d['status'] == 'finished':
            print('Done downloading, now converting ...')
            os.system("espeak -a 30 -p 99 'Just. downloaded. " + d['filename'].replace(".webm","").replace(" ", ". ") + "'")
            print("espeak -a 30 -p 99 'Just downloaded " + d['filename'].replace(".webm","") + "'")


        else:
            pass
        return

    @cherrypy.expose
    def downloadSong(self, name=None, url=None):

        if url!=None:

            ydl_opts = {
                'format': 'bestaudio',
                'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '320',
                }],
                'logger': MyLogger(),
                'progress_hooks': [self.my_hook],
                'outtmpl': '%(title)s.%(ext)s'
            }

            if name!=None:
                ydl_opts['outtmpl'] = name+'.%(ext)s'

            else:
                with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                    name = ydl.extract_info(url=url, download=False)['title']
                ydl_opts['outtmpl'] = name+'.%(ext)s'


            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
                self.playList(name+".mp3")
        return

    @cherrypy.expose
    def sacar(self):
        return open("sacar.html")

    @cherrypy.expose
    def dl(self,url):

        try:
            ydl_opts = {
                'format': 'bestaudio',
                'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'mp3',
                    'preferredquality': '320',
                }],
                'logger': MyLogger(),
                'progress_hooks': [self.my_hook],
                'outtmpl': '%(title)s.%(ext)s'
            }
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                name = ydl.extract_info(url=url, download=False)['title']
            ydl_opts['outtmpl'] = "musica"+'.%(ext)s'


            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
            return "musica" + '.mp3'

        except Exception as e:
            return "Error"


if __name__ == '__main__':

    conf = {

        'global': {
            'server.socket_host': '0.0.0.0',
            'server.socket_port': 80
        },
        '/': {
            'tools.sessions.on': True,

            'cors.expose.on': True,

            'tools.staticdir.root': os.path.abspath(os.getcwd()),
            'tools.staticdir.on': True,
            'tools.staticdir.dir': './'
        },
    }
    cherrypy.config.update({'server.socket_host': '0.0.0.0'})
    cherrypy.quickstart(Root(), "/", conf)
