
import kikimr.public.sdk.python.persqueue.grpc_pq_streaming_api as pqlib
import kikimr.public.sdk.python.persqueue.auth as pqauth
import ticket_parser2

import os


def get_tvm_secret():
    return os.environ.get('TVM_BILLING_SECRET')


class Sender:
    Api = None
    CredProvider = None
    Configurator = None
    Producer = None
    MaxSeqNo = None

    def __init__(self):
        self.Api = pqlib.PQStreamingAPI('lbkx.logbroker.yandex.net', 2135)
        api_start_future = self.Api.start()
        result = api_start_future.result(timeout=60)
        print('api started with ', result)

        tvm_settings = ticket_parser2.TvmApiClientSettings(2030071,
                                                           self_secret=get_tvm_secret(),
                                                           dsts={'pq': 2001059})
        tvm_client = ticket_parser2.TvmClient(tvm_settings)
        self.CredProvider = pqauth.TVMCredentialsProvider(tvm_client, destination_alias='pq')

        self.Configurator = pqlib.ProducerConfigurator('/yc/yandex/billing-saas', "saas-billing-sender".encode())
        self.Producer = self.Api.create_producer(self.Configurator, credentials_provider=self.CredProvider)

        start_future = self.Producer.start()
        start_result = start_future.result(timeout=60)
        if start_result.HasField("init"):
            print("Producer start result was: {}".format(start_result))
            self.MaxSeqNo = start_result.init.max_seq_no
        else:
            raise RuntimeError("Producer failed to start with error {}".format(start_result))

    def send(self, data):
        self.MaxSeqNo += 1
        response = self.Producer.write(self.MaxSeqNo, data.encode())
        write_result = response.result(timeout=15)
        if not write_result.HasField("ack"):
            raise RuntimeError("Message write failed with error {}".format(write_result))
