from urllib.parse import quote
from uuid import uuid4

from django.conf import settings
from django.template import loader
from django.utils.datastructures import OrderedSet


def _encode_query_value(value):
    if isinstance(value, bool):
        return str(value).lower()
    return str(value)


def _fold_query_params(params):
    result = []
    for key, value in params.items():
        values = value if isinstance(value, (list, tuple, OrderedSet)) else [value]
        result.extend(
            '%s=%s' % (key, _encode_query_value(v))
            for v in values if v is not None
        )
    return '&'.join(result)


def create_tracker_approvement_comment(issue_key, author, approvers=None, text='',
                                       is_parallel=None, uid=None, groups=None):
    """
    Создает коммент с iframe'ом на предзаполненную форму согласования в OK.
    """
    params = {
        '_embedded': 1,
        'object_id': issue_key,
        'author': author,
        'users': OrderedSet(approvers or []),
        'text': quote(text.encode('utf-8')),
        'is_parallel': is_parallel,
        'uid': uid or uuid4().hex,
        'groups': groups or [],
    }
    url = '{ok_url}tracker?{query_params}'.format(
        ok_url=settings.OK_URL,
        query_params=_fold_query_params(params),
    )
    iframe = '{{iframe src="%s" frameborder=0 width=100%% height=400px scrolling=no}}' % url
    return loader.render_to_string('startrek/ok/approvement.wiki', {'iframe': iframe})
