#! /usr/bin/python2.7 -tt
import socket
import sys

MESSAGE = "HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: %d\r\n\r\n%s\r\n\r\n"
ERROR_MESSAGE="""HTTP/1.1 404 Not Found\r\nContent-type: text/html\r\nContent-length: 113
\r\n\r\n<html><head><title>Not Found</title></head><body>\r\nSorry, the object you requested was not found.
\r\n</body></html>\r\n\r\n"""
ADDRESS = "/counter"
MATCH = 1
NO_MATCH = 0
NOT_FOUND = -1
HTTP_MESSAGE_SUFFIX_LENGHT = 4
BUFFER_SIZE = 4096

def find_get_index(lst) :
    for index in range(len(lst)):
        if lst[index] == "GET":
            return index
    return NOT_FOUND

def send_message(message):
    message_to_send_size_bytes = len(message)
    total_amount_of_bytes_sent = 0
    while (True):
        bytes_sent = s.send(message)
        if (bytes_sent<=0):
            break
        total_amount_of_bytes_sent += bytes_sent
        if(total_amount_of_bytes_sent == message_to_send_size_bytes):
            break
        message=message[bytes_sent:]

def process_http_request(http_request, requests_counter):
     lines_list = http_request.split("\r\n")
     first_line_words=lines_list[0].split()
     get_index = find_get_index(first_line_words)
     if get_index == NOT_FOUND or first_line_words[get_index+1] != ADDRESS:
         send_message(ERROR_MESSAGE)
         return NO_MATCH
     num_of_requests = str(requests_counter + 1)
     send_message(MESSAGE%(len(num_of_requests),num_of_requests))
     return MATCH
    

if __name__ == "__main__":
    requests_counter = 0
    total_data = ""
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    s.connect(('localhost',int(sys.argv[1])))
    while (True):
        data = s.recv(BUFFER_SIZE)
        if not data:
            break
        total_data += data
        find_http_index = total_data.find("\r\n\r\n")
        if(find_http_index != NOT_FOUND):
            http_request=total_data[:find_http_index + HTTP_MESSAGE_SUFFIX_LENGHT]
            total_data = total_data[find_http_index + HTTP_MESSAGE_SUFFIX_LENGHT:]
            requests_counter += process_http_request(http_request, requests_counter)
    s.close()