#!/usr/bin/env python3
import socket
import sys
import ssl

# default values
NUID = '001489806'
HOST = '3700.network'
PORT = 27993

# obtain information from server and respond to messages
HELLO = 'cs3700fall2020 HELLO ' + NUID + '\n'

# Usage: ./client <-p port> <-s> [hostname] [NEU ID]
args = sys.argv
port_flag = '-p' in args
ssl_flag = '-s' in args

# check if optional -p flag is properly set up or not used
valid_port = (port_flag and args[port_flag + 1].isdigit()) or not port_flag

# connect server using encrypted SSL version if optional -s flag is on
context = None
if ssl_flag:
    PORT = 27994
    context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)

if 2 < len(args) < 6 and args[-1].isdigit() and valid_port:
    if port_flag:
        PORT = int(args[port_flag + 1])
    HOST = args[-2]
    NUID = args[-1]
else:
    print('Usage: ./client <-p port> <-s> [hostname] [NEU ID]')
    sys.exit(1)


# creates TCP/IP socket
# sockets enable data transfer with the Internet via API
# AF_INET = IPv4 address
# SOCK_STREAM = stream sockets
def create_socket():
    address = (HOST, PORT)
    try:
        if context:
            s = context.wrap_socket(socket.socket(socket.AF_INET, socket.SOCK_STREAM))
        else:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(address)
        return s
    except OSError:
        s.close()
        s = None

    if s is None:
        print('Socket connection failed. Stoopid')
        sys.exit(1)


def process_msg(s, msg_type):
    s.send(msg_type.encode())
    msg = ''
    while '\n' not in msg:
        msg += s.recv(8196).decode()
    return msg.strip()


def count_keys(s):
    jumbalaya = process_msg(s, HELLO)
    while "BYE" not in jumbalaya:
        msg = jumbalaya.split()
        if msg[1] == 'BYE':
            s.close()
            return msg
        key = msg[2]
        key_count = str(msg[3].count(key))
        COUNT = 'cs3700fall2020 COUNT ' + key_count + '\n'
        jumbalaya = process_msg(s, COUNT)
    return jumbalaya


socket = create_socket()
secret_flag = count_keys(socket).split()[2]
print(secret_flag)
