from concurrent import futures
from rich.console import Console
from mpai_cae_arp.files import File, FileType
from mpai_cae_arp.types.irregularity import IrregularityFile
import grpc
from mpai_cae_arp.network import arp_pb2_grpc as arp_pb2_grpc
from mpai_cae_arp.network.arp_pb2 import (
    ComputationRequest,
    ComputationResult,
    Contact,
    Info,
    License,
)
import time

info = File('config/server.yaml', FileType.YAML).get_content()


class AudioAnalyserServicer(arp_pb2_grpc.AudioAnalyserServicer):

    def __init__(self, console: Console):
        self.console = console

    def getAimInfo(self, request, context) -> Info:
        self.console.log('Received request for AIM info')
        return Info(
            title=info['title'],
            description=info['description'],
            version=info['version'],
            contact=Contact(
                name=info['contact']['name'],
                email=info['contact']['email'],
            ),
            license=License(
                name=info['license_info']['name'],
                url=info['license_info']['url'],
            )
        )

    def analyse(self, request: ComputationRequest, context):

        working_dir: str = request.working_dir
        files_name: str = request.files_name

        self.console.log('Received request for computation')
        for x in range(10):
            yield ComputationResult(
                success=True,
                message=f'Processing {x * 10}%'
            )
            time.sleep(2)


def serve(console):
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    arp_pb2_grpc.add_AudioAnalyserServicer_to_server(AudioAnalyserServicer(console), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()


if __name__ == '__main__':
    console = Console()
    console.print('Server started at localhost:50051 :satellite:')
    serve(console)