import struct


def parse_task_packet(packet, offset=0):
    """
    Parse a result packet-

        [2 bytes] - type
        [2 bytes] - total # of packets
        [2 bytes] - packet #
        [2 bytes] - task/result ID
        [4 bytes] - length
        [X...]    - result data

        +------+--------------------+----------+---------+--------+-----------+
        | Type | total # of packets | packet # | task ID | Length | task data |
        +------+--------------------+--------------------+--------+-----------+
        |  2   |         2          |    2     |    2    |   4    | <Length>  |
        +------+--------------------+----------+---------+--------+-----------+

    Returns a tuple with (responseName, length, data, remainingData)

    Returns a tuple with (responseName, totalPackets, packetNum, resultID, length, data, remainingData)
    """
    try:
        packetType = struct.unpack('=H', packet[0 + offset:2 + offset])[0]
        totalPacket = struct.unpack('=H', packet[2 + offset:4 + offset])[0]
        packetNum = struct.unpack('=H', packet[4 + offset:6 + offset])[0]
        resultID = struct.unpack('=H', packet[6 + offset:8 + offset])[0]
        length = struct.unpack('=L', packet[8 + offset:12 + offset])[0]
        packetData = packet[12 + offset:12 + offset + length].decode('UTF-8')
        remainingData = packet[12 + offset + length:].decode('UTF-8')

        return (packetType, totalPacket, packetNum, resultID, length, packetData, remainingData)
    except Exception as e:
        print("parse_task_packet exception:", e)
        return (None, None, None, None, None, None, None)