#!/usr/bin/python3

import os
import subprocess
import sys
import tempfile

VIM_EXEC = "/usr/bin/nvim-qt"
COPY_CHUNK = 65#536

# TODO:
# - que abra "repetido en el mismo lugar?"
# - que abra dir distinto que file?
# - que siempre loguee a syslog?


def modo_stdin(_):
    print("========= NGV! stdin")
    temp_fd, temp_filepath = tempfile.mkstemp(prefix="ngv-")
    bytesin = sys.stdin.buffer
    while True:
        data = bytesin.read(COPY_CHUNK)
        # FIXME: log!
        print("========= copiados:", len(data))
        if not data:
            break
        os.write(temp_fd, data)
    cmd = [VIM_EXEC, "--nofork", temp_filepath]
    print("============= cmv", cmd)
    try:
        subprocess.run(cmd)
    except Exception as err:
        print("========= cmd err!", repr(err))
    finally:
        os.unlink(temp_filepath)


if len(sys.argv) == 2 and sys.argv[1] == "-":
    runner = modo_stdin
else:
    runner = modo_default

runner(sys.argv[1:])
# FIXME: except hook, log!
