#    guppy Copyright (C) 2010-2011 guppy team members.
#
#    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
#    This is free software, and you are welcome to redistribute it
#    under certain conditions; type `show c' for details.
#  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 2 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, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#  MA 02110-1301, USA.
# yt module
# --gry

import urllib.request, urllib.parse, urllib.error
#import socket
import json
import re


@plugin
class yt(object):
    """`yt <id here>` to see a Youtube.com video information (title, ups, down, time, &c)."""
    def __init__(self, server):
        self.server = server
        self.commands = ["yt"]
        self.server.handle("command", self.handle_command, self.commands)

    def handle_command(self, channel, user, cmd, args):
        if cmd == "yt":
            if len(args) < 1:
                self.server.doMessage(channel, user + ": Return http://youtube.com video information by URL or id. Syntax: yt <video url or id>.")
                return
            self.yt(channel, user, cmd, args)
    def yt(self, channel, user, cmd, args):
            request = re.sub(r"(?i)(?:https?://)?(?:www.)?(?:youtube.com/watch\?v=|youtu\.be/)([\w-]+)(?:[?&].*)?", r"\1", " ".join(args))
            print("Request is `" + request + "`.")
            sock = urllib.request.urlopen("http://gdata.youtube.com/feeds/api/videos/%s?v=2&alt=json" % request)
            data = sock.read().decode("utf-8")
            sock.close()
            try:
                e = json.loads(data)["entry"]
            except:
                self.server.doMessage(channel, user + ": No data found.")
                return
            e = json.loads(data)["entry"]
            h = int(e["media$group"]["yt$duration"]["seconds"]) // 3600
            m = int(e["media$group"]["yt$duration"]["seconds"]) // 60 - h * 60
            s = int(e["media$group"]["yt$duration"]["seconds"]) - h * 3600 - m * 60
            self.server.doMessage(channel, user + ": " + "'{0}' by {1} ({2}:{3}:{4}) - Rating {5} - Favorite {6}/{7} - Date {8} - Likes {9}+ {10}- /{11} http://youtu.be/{12}".format(
            e["title"]["$t"],
            e["author"][0]["name"]["$t"],
            h, m, s,
            e['gd$rating']['average'],
            e["yt$statistics"]["favoriteCount"],
            e["yt$statistics"]["viewCount"],
            e["published"]["$t"].split('.')[0].split("T")[0],
            #e["link"][0]["href"].encode('utf-8').replace("&feature=youtube_gdata", ""),
            e["yt$rating"]["numLikes"],
            e["yt$rating"]["numDislikes"],
            int(e["yt$rating"]["numLikes"]) - int(json.loads(data)["entry"]["yt$rating"]["numDislikes"]),
            request
            )
            )