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

import mllp_grpc.sim_mt_system_pb2_grpc as sim_mt_system_pb2_grpc
import mllp_grpc.sim_mt_system_pb2 as sim_mt_system_pb2
import mllp_grpc.sim_mt_common_pb2 as sim_mt_common_pb2
import google.protobuf.empty_pb2 as empty_pb2

class LazzyIterator:

    def __init__(self,i):
        self._i= i
        self._cv= threading.Condition()
        self._ready= False

    def __call__(self):
        with self._cv:
            if not self._ready:
                self._cv.wait()
        for v in self._i:
            yield v
                
    def ready(self):
        with self._cv:
            self._ready= True
            self._cv.notify()
        
# end LazzyIterator

def get_data(args):
    Log.info("Loading '%s'"%args.txt)
    Log.info('Sending data')
    with open(args.txt) as f:
        for l in f:
            l= l.strip().split()
            if l==[]: continue
            for w in l:
                o= sim_mt_common_pb2.TextPackage(words_novar=[w],
                                                 words_var=[],
                                                 eos=False)
                yield o
            o= sim_mt_common_pb2.TextPackage(words_novar=[],
                                             words_var=[],
                                             eos=True)
            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='txt file to translate')
    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_system_pb2_grpc.SimMTSystemStub(channel)
        info= stub.GetSystemInfo(empty_pb2.Empty())
        stub.SetEnabled(sim_mt_system_pb2.SetEnabledRequest(value=True))
        print(info)
        data= LazzyIterator(get_data(args))
        for o in stub.Translate(data()):
            if o.status.code==sim_mt_common_pb2.TranslateResponse.Status.READY:
                data.ready()
                continue
            if o.status.code!=sim_mt_common_pb2.TranslateResponse.Status.OK:
                print(o)
            else:
                for w in o.words_novar:
                    sys.stdout.write(w+' ')
                if o.eos: sys.stdout.write('\n')
                sys.stdout.flush()
        print('------------------------------------------------')
        
if __name__=='__main__':
    Log.basicConfig(level=Log.INFO)
    args= parse_cmdline()
    run(args)
