#!/usr/bin/python

# 1) pip install danmu
# 2) add `input-ipc-server=~~home/mpv.socket` to ~/.config/mpv/mpv.conf

import json
import os
import socket
import sys

from danmu import DanMuClient

mpv_socket = os.path.join(os.path.dirname(__file__), '../mpv.socket')
mpv_client = socket.socket(socket.AF_UNIX)
mpv_client.connect(mpv_socket)


class MPVError(Exception):
    pass


def pp(msg):
    print(msg.encode(sys.stdin.encoding, 'ignore').
          decode(sys.stdin.encoding))


def mpv_cmd(cmd):
    data = json.dumps(cmd).encode('utf8', 'strict') + b"\n"
    while data:
        size = mpv_client.send(data)
        if size == 0:
            raise MPVError('broken sender socket')
        data = data[size:]
    data = mpv_client.recv(4096)
    return data


def mpv_danmu(user, text):
    # pp(msg)
    cmd = {
        'command': ['script-message-to', 'danmu', 'danmu', user, text]
        # 'command': ['script-message', 'osc-message', user .. ': ' .. text]
    }
    try:
        mpv_cmd(cmd)
    except:
        os._exit(0)


def get_info():
    url = mpv_cmd({'command': ['get_property', 'path']})
    url = json.loads(url)
    url = url['data']
    title = mpv_cmd({'command': ['get_property', 'media-title']})
    title = json.loads(title)
    title = title['data']
    return (url, title)

url, title = get_info()
dmc = DanMuClient(url)
dmc.default(None)
dmc.gift(None)

if not dmc.isValid():
    mpv_danmu('Danmu', 'Url not valid')
else:
    mpv_danmu('', title)
    mpv_danmu('', url)


@dmc.danmu
def danmu_fn(msg):
    if msg['Content'].isdigit():
        return
    mpv_danmu(msg['NickName'], msg['Content'])


dmc.start(blockThread=True)
