import json
import time
import os.path as path


class Module:
    def __init__(self, incoming=False, verbose=False, options=None):
        # extract the file name from __file__. __file__ is proxymodules/name.py
        self.name = path.splitext(path.basename(__file__))[0]
        self.description = 'Simply print the received data as text'
        self.incoming = incoming  # incoming means module is on -im chain
        self.find = None  # if find is not None, this text will be highlighted

    # protocol 2: flag{n3v3r_tru5t_b0b}
    def execute(self, data):
        print(f"Incoming data: {data}")
        data_json = json.loads(data)
        
        # return handshake messages without modification
        if data_json.get("type") == "HANDSHAKE":
            return data
        
        # swap receiver and sender of protocol messages with id 1,2 or 3
        elif data_json.get("id") in {1, 2, 3}:
            data_json["sender"], data_json["receiver"] = data_json["receiver"], data_json["sender"]

        # if message 3 received from Alice, build valid message 4
        if data_json.get("id") == 3:
            data_json["id"] = 4
            data_json["content"] = str(int(time.time()))

        # dump message
        data = json.dumps(data_json) + "\n"
        print(f"Outgoing data: {data}")

        # return crafted message to proxy
        return data


if __name__ == '__main__':
    print('This module is not supposed to be executed alone!')
