#!/opt/local/Library/Frameworks/Python.framework/Versions/3.10/bin/python3.10
# -*- coding: utf-8 -*-

# Copyright 2019-2020 Daniel Estevez <daniel@destevez.net>
#
# This file is part of gr-satellites
#
# SPDX-License-Identifier: GPL-3.0-or-later
#

import subprocess
import sys

import numpy as np

from satellites.kiss import *


def print_usage():
    print(f'Usage {sys.argv[0]} <jy1sat_frames.kss> <output_path>')


def seqnum(packet):
    return packet[3]*256 + packet[4]


def read_kiss_file(path):
    frames = list()
    frame = list()
    framesize = 256
    transpose = False
    with open(path, 'rb') as f:
        for c in f.read():
            if c == FEND:
                if len(frame) == framesize + 1 and (frame[0] & 0x0f) == 0:
                    frames.append(frame[1:])
                frame = list()
            elif transpose:
                if c == TFEND:
                    frame.append(FEND)
                elif c == TFESC:
                    frame.append(FESC)
                transpose = False
            elif c == FESC:
                transpose = True
            else:
                frame.append(c)
    return np.array(frames, dtype='uint8')


def main():
    if len(sys.argv) != 3:
        print_usage()
        sys.exit(1)

    input_file = sys.argv[1]
    output_file = sys.argv[2]

    # Read 256 byte frames
    x = read_kiss_file(input_file)

    # Filter out by frame id and trim to payload
    x = x[((x[:, 0] == 0xe0) | (x[:, 0] == 0xe1)) & (x[:, 1] == 0x10), 56:]

    # Filter SSDV packets
    x = x[(x[:, 0] == 0x55) & (x[:, 1] == 0x68), :]
    ids = set(x[:, 2])

    for i in ids:
        L = list(x[x[:, 2] == i, :])
        L.sort(key=seqnum)
        ssdv = '{}_{}.ssdv'.format(output_file, i)
        jpeg = '{}_{}.jpg'.format(output_file, i)
        np.array(L).tofile(ssdv)
        print('Calling SSDV decoder for image {}'.format(hex(i)))
        subprocess.call(['ssdv', '-d', '-J', ssdv, jpeg])
        print()


if __name__ == '__main__':
    main()
