# -*- coding: utf-8 -*-
import operator

from django.db.models import Q

from pytils.translit import translify

from functools import reduce


def clean_url_protocol(full_url, is_secure=False):
    if not full_url.startswith('http://') and not full_url.startswith('https://'):
        if is_secure:
            prefix = 'https://'
        else:
            prefix = 'http://'

        full_url = '%s%s' % (prefix, full_url)

    return full_url


class ORMFullTextSearchConstructor(object):
    """
    TODO: move tests from
    /Users/web-chib/Dropbox/develop/yandex/events/events/accounts/tests/conditions/profile/is_fit_for_search_text.py
    and test this class instead
    """

    def __init__(self, prefix, localizable_params=None, not_localizable_params=None, is_full_text_search=False):
        self.prefix = prefix
        self.localizable_params = localizable_params or []
        self.not_localizable_params = not_localizable_params or []
        self.all_params = self.localizable_params + self.not_localizable_params
        self.is_full_text_search = is_full_text_search

    def get_q_objects_for_text(self, search_text):
        search_text = search_text.split('\u2192')[-1]
        parts = search_text.split(' ')
        conditions = []
        if self.is_full_text_search:
            query_type = 'icontains'
        else:
            query_type = 'istartswith'
        query_type = '__{0}'.format(query_type)
        for part in parts:
            full_condition_parts = []
            part_translit = translify(part)
            for param in self.all_params:
                full_condition_parts.append(Q(**{param + query_type: part}))
                full_condition_parts.append(Q(**{param + query_type: part_translit}))
            conditions.append(reduce(operator.or_, full_condition_parts))
        return reduce(operator.and_, conditions)
