"""
Authors:
Kumar Shridhar <shridhar.stark@gmail.com>
Venkatesh Iyer <iyervenkatesh92@gmail.com>
Ritu Yadav <er.ritu92@gmail.com>

Code modified from : https://github.com/egbertbouman/youtube-comment-downloader

"""

import lxml.html
from lxml.cssselect import CSSSelector


def extract_comments(html):
    tree = lxml.html.fromstring(html)
    item_sel = CSSSelector(".comment-item")
    text_sel = CSSSelector(".comment-text-content")
    time_sel = CSSSelector(".time")
    author_sel = CSSSelector(".user-name")
    vote_sel = CSSSelector(".like-count.off")
    photo_sel = CSSSelector(".user-photo")

    for item in item_sel(tree):
        yield {
            "id": item.get("data-cid"),
            "content": text_sel(item)[0].text_content(),
            "time": time_sel(item)[0].text_content().strip(),
            "author": author_sel(item)[0].text_content(),
            "votes": vote_sel(item)[0].text_content() if len(vote_sel(item)) > 0 else 0,
            "photo": photo_sel(item)[0].get("src"),
        }


def extract_reply_cids(html):
    tree = lxml.html.fromstring(html)
    sel = CSSSelector(".comment-replies-header > .load-comments")
    return [i.get("data-cid") for i in sel(tree)]
