"""
This script is controlled by constant SHARE_PART_NUM and designed to collect shares object, to decide and check which
ones are more liquid
"""

import tinkoff_grpc
import time
import grpc
import argparse
import market_trade.constants


# initialized argument parser
arguments_parser = argparse.ArgumentParser(description="A simple shares data collector")

# added part number controller
arguments_parser.add_argument("-p", "--part-number", type=int, action="store",
                              dest=market_trade.constants.PART_NUMBER_FIELD,
                              default=market_trade.constants.DEFAULT_PART_NUMBER)


def get_share_part(part_number, channel):
    """
    This function returns list of shares based on limit and controlling constant `SHARE_PART_NUM`
    :param part_number: int, a number indicating which shares part should we collect now
    :param channel: tinkoff_grpc.Channel object, which helps to initialize the service
    :return: shares, list of Share objects
    """

    # initializing the service
    instrument_service = tinkoff_grpc.InstrumentsService(channel)

    # getting list of all shares
    shares = instrument_service.get_shares(market_trade.constants.DEFAULT_INSTRUMENT_STATUS)

    # getting part indices, based on the constant PART NUM
    start_share_idx = part_number * market_trade.constants.MARKETDATA_CONNECTION_LIMIT_SUBSCRIPTIONS
    end_share_idx = (part_number+1) * market_trade.constants.MARKETDATA_CONNECTION_LIMIT_SUBSCRIPTIONS

    # if the length of shares is smaller than end index, make it just the last share element
    if end_share_idx > len(shares):
        end_share_idx = -1

    # getting our shares
    shares_to_check = shares[start_share_idx: end_share_idx]
    return shares_to_check


if __name__ == '__main__':
    # getting our arguments parsed and converting them to dict
    cli_args = vars(arguments_parser.parse_args())

    api_address = market_trade.constants.TINKOFF_API_ADDRESS
    token = market_trade.constants.TINKOFF_BEARER_TOKEN
    authorization_field = market_trade.constants.TINKOFF_AUTHORIZATION_HEADER
    with tinkoff_grpc.Channel(api_address=api_address,
                              token=token,
                              authorization_field=authorization_field) as tinkoff_channel:
        # getting target share part
        shares_part = get_share_part(cli_args[market_trade.constants.PART_NUMBER_FIELD], channel=tinkoff_channel)
        while True:
            time.sleep(1)
            try:
                tinkoff_trades_saver = tinkoff_grpc.savers.TradesSaver(channel=tinkoff_channel, instruments=shares_part,
                                                                       filepath=market_trade.constants.SHARES_TRADES_PATH)
                tinkoff_trades_saver.start()
            except grpc.RpcError as grpc_error:
                pass
