'''
    Server main file
    Server code is dependent on Twisted library, but not on Kivy library
'''

import argparse

from twisted.internet import reactor
from twisted.internet import protocol

from core.message_passing_protocol import MessagePassingProtocol
from core.file_manager import FileManager
from core.network_interface import NetworkInterface

# function to parse command line arguments
def parse_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--port', type=int, default=8883, help='Port on which the server will listen. Default value 8883 if not specified.')
    args, unknown = parser.parse_known_args()
    return args

def main():
    custom_args = parse_arguments()
    port_to_listen = custom_args.port

    # initialize file saving directories
    # use the server port to separate different server folders on the same machine
    #  (useful for testing multiple servers on locally)
    if not FileManager.init_save_path(specific_id=port_to_listen):
        # file saving not working correctly, we should not run the server
        print("FileManager initialization... [FAILED]. Stopping.")
        return
    else:
        print("FileManager initialization... [OK]")
    
    factory = protocol.ServerFactory()
    factory.protocol = MessagePassingProtocol
    factory.is_server = True
    
    reactor.callLater(20, NetworkInterface.server_init_task, port_to_listen)

    print("Server started on port:", port_to_listen)
    reactor.listenTCP(port_to_listen,factory)
    reactor.run()

if __name__ == '__main__':
    main()
