import socket
import threading
import time
from tcp_packet import TCPPacket
from ip_layer import IPLayer

# from utils import net_params

class TCPSocket:

    _localport = 1234
    _ip_layer = None

    ip = None       # ip назначения
    port = None     # port назначения

    next_seq_num = 0
    next_ack_num = 0

    send_data = ""
    recv_data = ""

    def __init__(self, ip_layer):
        self._ip_layer = ip_layer
        recv_thread = threading.Thread(target=self._recv_thread, daemon=True)
        send_thread = threading.Thread(target=self._send_thread, daemon=True)
        recv_thread.start()
        send_thread.start()


    def send(self, data):
        self.send_data += data


    def _send(self, packet):
        packet.SEQ = self.next_seq_num

        if packet.ACK == 1: 
            packet.ACK = self.next_ack_num
        if (packet.f_SYN == 1 or packet.f_FIN == 1):
            self.next_seq_num = self.next_seq_num + 1
        elif (packet.f_ACK == 1 and len(packet.DATA) == 0):
            self.next_seq_num = self.next_seq_num
        elif (len(packet.DATA) != 0):
            self.next_seq_num = self.next_seq_num + len(packet.DATA)
        

        self._ip_layer.send(self.ip, packet.to_hex_string())


    def _recv_thread(self):
        while True:
            # print("This is recv thread")
            time.sleep(2)


    def _send_thread(self):
        while True:
            # print("This is send thread")
            time.sleep(1)


    def connect(self, ip, port):
        self.ip = ip
        self.port = port
        # print("Opening connection")

        # send SYN
        syn = self.make_tcp_packet()
        syn.f_SYN = 1
        print(syn)
        self._send(syn)


    def make_tcp_packet(self):
        packet = TCPPacket()
        packet.set_ip(IPLayer.get_ip_address(), self.ip)
        packet.SRC = self._localport # type: ignore
        packet.DST = self.port # type: ignore
        return packet



def main():
    ip_layer = IPLayer()
    sock = TCPSocket(ip_layer)
    # sock.connect("77.88.55.242", 80)   
    for i in range(2000):
        sock.connect("172.16.2.100", 80) 
        time.sleep(0.1)
    # lock_net = LocalNetwork()
    # print(lock_net.get_ip()) # type: ignore


if __name__ == "__main__":
    main()

