import saas.library.persqueue.writer.python.writer as saas_writer
import saas.protos.rtyserver_pb2 as rtyserver

import os
import logging
import sys
import json
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

service_name = 'ad_moderation'
servcie_ctype = 'prestable'
directory_with_topics = 'saas/services/{name}/{ctype}/topics'.format(name=service_name, ctype=servcie_ctype)

search_map_settings = saas_writer.SearchMapInputSettings()
search_map_settings.dm_host = 'saas-dm-proxy.n.yandex-team.ru'
search_map_settings.statica_host = 'saas-searchmap.s3.mds.yandex.net'
search_map_settings.statica_query = servcie_ctype
search_map_settings.ctype = servcie_ctype

src_tvm_client_id = int(os.getenv('TVM_CLIENT_ID'))
src_tvm_secret = os.getenv('TVM_SECRET')

logbroker_tvm_client_id = 2001059

logger = logging.getLogger("logbroker_log")
lb_logger = saas_writer.Logger(logger)

writer = None
while writer is None:
    settings = saas_writer.Settings()
    writer = saas_writer.Writer()
    try:
        settings.set_logger(lb_logger)
        settings.set_service_info(search_map_settings, service_name)
        settings.set_tvm(src_tvm_client_id, logbroker_tvm_client_id, src_tvm_secret)
        settings.set_persqueue_settings('logbroker.yandex.net', directory_with_topics)
        writer.init(settings)
    except Exception as e:
        logging.exception('Error in creating: {}'.format(e))
        writer = None

json_message = {'action': 'delete', 'docs': [{'url': 'fakeurl'}]}

proto_message = rtyserver.TMessage()
proto_message.MessageType = rtyserver.TMessage.DELETE_DOCUMENT
proto_message.Document.Url = 'fakeurl'

write_future_proto = writer.write_proto(proto_message)
write_future_json = writer.write_json(json_message)

logging.info('Write proto TMessage: {}'.format(json.dumps(
    write_future_proto.result()
)))
logging.info('Write json: {}'.format(json.dumps(
    write_future_json.result()
)))
