import grpc
import logging
from concurrent import futures

import tank_job_pb2
import tank_job_pb2_grpc


def save_chunk(chunk_message):
    logging.info('File chunk for {} received, job %s', chunk_message.file_type, chunk_message.tank_job)

    file_name = '{job_name}.{file_type}'.format(
        job_name=chunk_message.tank_job,
        file_type='config' if chunk_message.file_type == 0 else 'ammo'
    )
    with open(file_name, 'ab') as input_file:
        input_file.write(chunk_message.chunk_content)


class FileUploader(tank_job_pb2_grpc.TankJobServiceServicer):

    def UploadFile(self, request_iterator, context):
        for message in request_iterator:
            save_chunk(message)
        return tank_job_pb2.UploadResponse(upload_status=1)


class Server:

    @staticmethod
    def run():
        server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        tank_job_pb2_grpc.add_TankJobServiceServicer_to_server(FileUploader(), server)
        server.add_insecure_port('[::]:50051')
        server.start()
        server.wait_for_termination()


if __name__ == '__main__':
    Server.run()
