import logging as Log
import grpc,argparse,time,sys,threading

import mllp_grpc.sim_mt_pb2_grpc as sim_mt_pb2_grpc
import mllp_grpc.sim_mt_pb2 as sim_mt_pb2
import mllp_grpc.sim_mt_common_pb2 as sim_mt_common_pb2
import google.protobuf.empty_pb2 as empty_pb2


def get_data(args,sys_id):
    Log.info("Loading '%s'"%args.txt)
    Log.info('Sending data')
    yield sim_mt_pb2.TranslateRequest(system_id=sys_id)
    with open(args.txt) as f:
        for l in f:
            l= l.strip().split()
            if l==[]: continue
            for w in l:
                data= sim_mt_common_pb2.TextPackage(words_novar=[w],
                                                    words_var=[],
                                                    eos=False)
                o= sim_mt_pb2.TranslateRequest(text=data)
                yield o
            data= sim_mt_common_pb2.TextPackage(words_novar=[],
                                                    words_var=[],
                                                    eos=True)
            o= sim_mt_pb2.TranslateRequest(text=data)
            yield o
    Log.info('Transmission completed')
        
def parse_cmdline():
    p= argparse.ArgumentParser(description='Simultaneous MT GRPC client')
    p.add_argument('host',type=str,help='server host')
    p.add_argument('port',type=int,help='server port')
    p.add_argument('txt',type=str,help='input text file')
    args= p.parse_args()
    return args

def run(args):
    addr= '%s:%d'%(args.host,args.port)
    with grpc.insecure_channel(addr) as channel:
        stub= sim_mt_pb2_grpc.SimMTStub(channel)
        for info in stub.GetSystemsInfo(empty_pb2.Empty()):
            print(info)
        print_host= True
        for o in stub.Translate(get_data(args,0)):
            if print_host:
                print_host= False
                print(o.host_info)
            if o.status.code!=sim_mt_common_pb2.TranslateResponse.Status.Code.OK:
                print(o)
            else:
                for w in o.words_novar:
                    sys.stdout.write(w+' ')
                if o.eos: sys.stdout.write('\n')
                sys.stdout.flush()
        
if __name__=='__main__':
    Log.basicConfig(level=Log.INFO)
    args= parse_cmdline()
    run(args)
