#!/usr/bin/env python3
import include_homekit
import subprocess
import sys

from argparse import ArgumentParser, ArgumentError
from homekit.camera import IpcamConfig

if __name__ == '__main__':
    players = ('mpv', 'vlc')
    parser = ArgumentParser()
    parser.add_argument('--tcp', action='store_true',
                        help='use tcp for rtsp')
    parser.add_argument('--player', type=str, choices=players, default=players[0],
                        help='player to use')
    parser.add_argument('--low', action='store_true',
                        help='use second channel')
    parser.add_argument('camera', metavar='CAMERA', type=int, nargs=1,
                        help='number of camera to stream')
    args = parser.parse_args()

    ic = IpcamConfig()
    camera = args.camera[0]
    if not ic.has_camera(camera):
        raise ArgumentError(None, f'invalid camera {camera}')

    cmd = [args.player]
    if args.tcp:
        cmd.extend(['--rtsp-transport=tcp', '--force-seekable=yes'])
    ip = ic.get_camera_ip(camera)
    username, password = ic.get_rtsp_creds()
    uri = f'rtsp://{username}:{password}@{ip}:554'
    uri += ic.get_camera_type(camera).get_channel_url(1 if not args.low else 2)
    cmd.append(uri)

    p = subprocess.run(cmd, capture_output=False)
    if p.returncode != 0:
        print(f'error: {args.player} returned {p.returncode}', file=sys.stderr)