# coding: utf-8

from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import random


class SaasLog2Ammo(object):
    def __init__(self, saas_service_name, sample_ratio=1, replace_service=None,
                 strip_reqid=True, reqinfo=None):
        """
        :param saas_service_name: Name of saas service
        :param sample_ratio: sample ratio: 1 - return all rows, 5 - return one row from every 5
        """
        self._service_name = saas_service_name
        self._sample_ratio = sample_ratio if sample_ratio >= 1 else 1
        self._replace_service = replace_service
        self._strip_reqid = strip_reqid
        self._reqinfo = reqinfo

    def __call__(self, row):
        request_string = row['processed-query']
        if self._service_name == row['service'] and (
            self._sample_ratio == 1 or random.randint(1, self._sample_ratio) == self._sample_ratio
        ):
            if not (("&service=" in request_string) or request_string.startswith("service=")):
                request_string = '{}&service={}'.format(request_string, self._service_name)
            if self._replace_service:
                request_string = request_string.replace(
                    'service={}'.format(self._service_name),
                    'service={}'.format(self._replace_service)
                )
            if self._strip_reqid:
                request_string = request_string.replace('reqid={}'.format(self._service_name), '')
            if self._reqinfo:
                request_string = '{}&reqinfo={}'.format(request_string, self._reqinfo)
            req_str = '/?{}'.format(request_string)
            yield {'ammo': req_str}
