#!/usr/bin/python2.7 -tt

import sys
from socket import socket

END_OF_MSG = '\r\n\r\n'
MAX_SIZE_RECV = 1024
MSG = {
    'NOT_FOUND': 'HTTP/1.1 404 Not Found\r\n'
    'Content-type: text/html\r\n'
    'Content-length: 113\r\n\r\n'
    '<html><head><title>Not Found</title></head><body>\r\n'
    'Sorry, the object you requested was not found.\r\n'
    '</body></html>\r\n\r\n',

    'FOUND': 'HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\n\r\n{}\r\n\r\n'
}


class Server():
    def __init__(self):
        self._socket = socket()
        port = self.get_port_number_from_cmd()
        self._socket.connect(('localhost', port))
        self._request_counter = 0

    def get_and_handle_request(self):
        while True:
            recv_msg = self.recv_msg_from_lb()

            is_valid_msg = self.is_valid_msg(recv_msg)

            msg_to_send = self.get_msg_to_send(is_valid_msg)

            self._socket.send(msg_to_send.encode())

    def recv_msg_from_lb(self):
        recv_msg = ''

        while END_OF_MSG not in recv_msg:
            current_msg_segment = self._socket.recv(MAX_SIZE_RECV).decode()
            recv_msg += str(current_msg_segment)

        return recv_msg

    def get_msg_to_send(self, is_valid_msg):
        msg_to_send = MSG['NOT_FOUND']
        if is_valid_msg:
            self._request_counter += 1
            msg_to_send = MSG['FOUND'].format(len(str(self._request_counter)),
                                              str(self._request_counter))
        return msg_to_send

    def is_valid_msg(self, msg):
        if msg.startswith('GET /counter'):
            return True
        return False

    def get_port_number_from_cmd(self):
        return int(sys.argv[1])


server = Server()
server.get_and_handle_request()
