#!python

from datetime import datetime, timedelta
from socket import AF_INET, SOCK_STREAM, socket as Socket
from sys import argv, stderr
from dvrip import DVRIP_PORT
from dvrip.io import DVRIPClient
from dvrip.search import FileType


import dvrip.packet


def _read(file, length, _read=dvrip.packet._read):  # pylint: disable=protected-access
	data = _read(file, length)
	#print('recv', bytes(data) if data[:1].isascii() else data.hex(),
	#      file=stderr, flush=True)
	return data
dvrip.packet._read = _read  # pylint: disable=protected-access

def _write(file, data, _write=dvrip.packet._write):  # pylint: disable=protected-access
	print('send', bytes(data) if data[:1].isascii() else data.hex(),
	      file=stderr, flush=True)
	return _write(file, data)
dvrip.packet._write = _write  # pylint: disable=protected-access


conn = DVRIPClient(Socket(AF_INET, SOCK_STREAM))
conn.connect((argv[1], DVRIP_PORT), argv[2], argv[3])
print(conn.systeminfo())
print(conn.storageinfo())
print(conn.time(conn.time() - timedelta(seconds=0)))
now = datetime.now()
print(list(conn.search(start=now - timedelta(hours=5),
                       end=now,
                       channel=0,
                       type=FileType.VIDEO)))

name = '/idea0/2019-05-01/001/01.04.07-01.04.23[M][@15b7][0].h264'
sock = Socket(AF_INET, SOCK_STREAM)
sock.connect((argv[1], DVRIP_PORT))
in_ = conn.download(sock, name)
with open('test.264', 'wb') as out:
	while True:
		chunk = in_.read()
		if not chunk: break
		out.write(chunk)

#conn.reboot()
conn.logout()
