# coding: utf-8
import os, sys

from flask import Flask
from flask_cors import CORS
from webargs import fields
from webargs.flaskparser import use_args

# --http-header-fields=
DEFAULT_USER_AGENT = '\"referer:https://www.bilibili.com/\",\"user-agent: Mozil' \
                     'la/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (K' \
                     'HTML, like Gecko) Chrome/90.0.4430.72 Safari/537.36 Edg/90' \
                     '.0.818.39\"'
video_args = {
    'dir': fields.Str(required=True),
    'referer': fields.Str(required=True),
    'user-agent': fields.Str(),
    'urls': fields.List(fields.Str()),
    'titles': fields.List(fields.Str())
}

app = Flask(__name__)
CORS(app, resources=r'/*')  # To fix ajax CORS problem

def create_valid_url(url: str) -> str:
    """
    Generate a video direct play url.
    """
    return url


@app.route('/', methods=['GET', 'POST'])
@use_args(video_args)
def paly_with_mpv(args):
    """
    1. Handle requests and parse json file.
    2. Generate mpv args and mpv command.
    3. Execute mpv command.
    """
    if args['user-agent'] is None:
        args['user-agent'] = DEFAULT_USER_AGENT
    args['urls'] = map(create_valid_url, args['urls'])

    playlist_file = './_tmp_playlist.m3u'
    with open(playlist_file, 'w', encoding='utf-8') as f:
        # Whether delete the tmp playlist file? Look a time xixi.
        f.write('#EXTM3U\n')
        f.write('#Generated by Wullic-videoanywhere\n')
        for title, url in zip(args['titles'], args['urls']):
            f.write('#EXTINF:-1,' + title + '\n')
            f.write(url + '\n')

    mpv_httpd_header = '--http-header-fields=\"referer:{0}\",\"user-agent:{1}\"'.format(args['referer'], args['user-agent'])
    mpv_cmd = ' '.join([args['dir'], mpv_httpd_header, '--playlist=' + playlist_file ])

    print(mpv_cmd)
    print('\n'.join(args['titles']))
    ret = os.system(mpv_cmd)
    if ret != 0:
        return {'success': False,
                'message': 'MPV: command not found. Ensure your mpv path'}
    else :
        return {'success': True,
                'message': ''}

def main():
    """
    Command line program and run a server.
    """
    if sys.version_info < (3, 8):
        raise ValueError('This script is only for use with Python 3.8 or later')
    else:
        import argparse

        parser = argparse.ArgumentParser(description='Start a server to support '
                                                     'playing video urls with MPV.')
        parser.add_argument('-p', '--port', default=50000, dest='port',
                            help='choose the port that server '
                                 'listens to (default: 50000)')
        args = parser.parse_args()
        os.environ['FLASK_ENV'] = 'development'
        app.run(port=args.port, debug=True)
main()
