import sys
import time
import click
from datacloud.config.token_names import AUDIENCE_TOKEN_NAME
from datacloud.config.robots import AUDIENCE_ROBOT_NAME
from datacloud.dev_utils.yt import yt_utils
from datacloud.dev_utils.logging.logger import get_basic_logger
from datacloud.audience.lib.api import AudienceApi
from simplejson.errors import JSONDecodeError

logger = get_basic_logger(__name__)


@click.group()
def cli():
    pass


@cli.command('chmod')
@click.option('--share', 'share', flag_value='share')
@click.option('--revoke', 'share', flag_value='revoke')
@click.option('--user-id', required=True)
@click.option('--segment-id')
@click.option('--filename')
@click.option('--audience-token', envvar=AUDIENCE_TOKEN_NAME, required=True)
def access(share, user_id, segment_id, filename, audience_token):
    if share == 'share':
        chmod_single_segment = share_single_segment
    elif share == 'revoke':
        chmod_single_segment = revoke_single_segment
    else:
        logger.error('use `--share` or `--revoke`')
        sys.exit(1)

    yt_client = yt_utils.get_yt_client()
    api = AudienceApi(yt_client, AUDIENCE_ROBOT_NAME, audience_token)
    if segment_id:
        chmod_single_segment(api, segment_id, user_id)
    elif filename:
        with open(filename, 'r') as fh:
            idx = 1
            for segment_id in fh:
                segment_id = int(segment_id)
                resp = chmod_single_segment(api, segment_id, user_id)
                if resp.status_code != 200:
                    logger.error('Stop')
                    sys.exit(1)
                if idx % 10 == 0:
                    print('Sleep 1 minute')
                    time.sleep(60)
                idx += 1
    else:
        logger.error('provide `--segment-id` or `--filename`')
        sys.exit(1)


def share_single_segment(api, segment_id, user_id):
    response = api.share(segment_id, user_id)
    if response.status_code == 200:
        logger.info('Ok {} shared to {}'.format(segment_id, user_id))
    else:
        logger.warning('Fail: {}'.format(response.status_code))
        try:
            logger.warning('Error: {}'.format(response.json()['message']))
        except JSONDecodeError:
            logger.warning('Can not parse json')
    return response


def revoke_single_segment(api, segment_id, user_id):
    response = api.revoke(segment_id, user_id)
    if response.status_code == 200:
        logger.info('Ok {} revoked from {}'.format(segment_id, user_id))
    else:
        logger.warning('Fail: {}'.format(response.status_code))
        try:
            logger.warning('Error: {}'.format(response.json()['message']))
        except JSONDecodeError:
            logger.warning('Can not parse json')
    return response


if __name__ == '__main__':
    cli()
