# coding=utf-8

from copy import copy
from xml.etree import cElementTree as ET

from lulu.common import (
    url_info,
    print_info,
    get_content,
    download_urls,
    playlist_not_supported,
)


__all__ = ['ckplayer_download']
site_info = 'CKPlayer General'


def ckplayer_get_info_by_xml(ckinfo):
    """str->dict
    Information for CKPlayer API content.
    """
    e = ET.XML(ckinfo)
    video_dict = {
        'title': '',
        'links': [],
        'size': 0,
        'flashvars': '',
    }
    dictified = dictify(e)['ckplayer']
    if 'info' in dictified:
        if '_text' in dictified['info'][0]['title'][0]:  # title
            video_dict['title'] = dictified['info'][0]['title'][0][
                '_text'
            ].strip()

    if '_text' in dictified['video'][0]['size'][0]:  # size exists for 1 piece
        video_dict['size'] = sum(
            [int(i['size'][0]['_text']) for i in dictified['video']]
        )

    if '_text' in dictified['video'][0]['file'][0]:  # link exist
        video_dict['links'] = [
            i['file'][0]['_text'].strip() for i in dictified['video']
        ]

    if '_text' in dictified['flashvars'][0]:
        video_dict['flashvars'] = dictified['flashvars'][0]['_text'].strip()

    return video_dict


# helper
# https://stackoverflow.com/questions/2148119/how-to-convert-an-xml-string-to-a-dictionary-in-python  # noqa
def dictify(r, root=True):
    if root:
        return {r.tag: dictify(r, False)}
    d = copy(r.attrib)
    if r.text:
        d['_text'] = r.text
    for x in r.findall('./*'):
        if x.tag not in d:
            d[x.tag] = []
        d[x.tag].append(dictify(x, False))
    return d


def ckplayer_download_by_xml(
    ckinfo, output_dir='.', merge=False, info_only=False, **kwargs
):
    # Info XML
    video_info = ckplayer_get_info_by_xml(ckinfo)

    try:
        title = kwargs['title']
    except Exception:
        title = ''
    type_ = ''
    size = 0

    if len(video_info['links']) > 0:  # has link
        # use 1st to determine type, ext
        type_, _ext, size = url_info(video_info['links'][0])

    if 'size' in video_info:
        size = int(video_info['size'])
    else:
        for i in video_info['links'][1:]:  # save 1st one
            size += url_info(i)[2]

    print_info(site_info, title, type_, size)
    if not info_only:
        download_urls(
            video_info['links'], title, _ext, size, output_dir=output_dir,
            merge=merge
        )


def ckplayer_download(
    url, output_dir='.', merge=False, info_only=False, is_xml=True, **kwargs
):
    if is_xml:  # URL is XML URL
        try:
            title = kwargs['title']
        except Exception:
            title = ''
        try:
            headers = kwargs['headers']  # headers provided
            ckinfo = get_content(url, headers=headers)
        except NameError:
            ckinfo = get_content(url)

        ckplayer_download_by_xml(
            ckinfo, output_dir, merge, info_only, title=title
        )


download = ckplayer_download
download_playlist = playlist_not_supported(site_info)
