#   Copyright (C) 2022 Stephen Fairchild (s-fairchild@users.sourceforge.net)
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 2 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program in the file entitled COPYING.
#   If not, see <http://www.gnu.org/licenses/>.

__all__ = ["main"]

_description_ = "Launch backend and keep pinging it."

import ctypes
import os
import time
from datetime import datetime

from idjc import FGlobs, PGlobs


def main():
    print(_description_)

    backend = ctypes.CDLL(FGlobs.backend)

    read = ctypes.c_int()
    write = ctypes.c_int()
    if not backend.init_backend(ctypes.byref(read), ctypes.byref(write)):
        print("call to init_backend failed")
        return 5

    print(f"file descriptors for read/write are {read.value}, {write.value}")

    try:
        backend_write = os.fdopen(write.value, "w")
        backend_read = os.fdopen(read.value, "r")
    except OSError:
        "failed to open streams to backend"
        return 5

    print("awaiting reply")

    try:
        line = backend_read.readline()
    except IOError as e:
        print(e)
        return 5

    if line != "idjc backend ready\n":
        print(f"bad reply from backend: {line}")
        return 5

    print(f"backend replies with: {line}")

    def ping():
        print("sending ping")
        try:
            backend_write.write("mx\nACTN=ping\nend\n")
            backend_write.flush()
            reply = backend_read.readline().rstrip() or "(none)"
            print(f"reply: {reply}")
            if reply != "pong":
                raise ValueError
        except IOError as e:
            print(f"unexpected error: {e}")
            reply = str(e)
        except ValueError:
            print(f"normally we expect pong reply: got {reply} instead")

        return reply

    start_time = datetime.now()

    while ping() == "pong":
        print(f"time elapsed = {datetime.now() - start_time}")
        time.sleep(2)

    return 0
