# -*- coding: utf-8 -*-

from django.http import HttpResponse
import json
import csv
from .mailSender import techSendMail

import re

numbers = '0123456789.,'


def get_fieldsNames_of_model(model):

    fields_names = [item.name for item in model._meta.get_fields()]
    return fields_names



def get_unique_url(model, name, url=None):
    from .functions import url_translit

    if not url:
        url = url_translit(name)

    try:
        obj = model.objects.get(url=url)
    except model.DoesNotExist:
        return url

    urls = model.objects.all().values_list('url', flat=True)

    i = 1
    while url in urls:
        url = f'{url}-{i}'
        i += 1

    return url


def dicts_join(dict1, dict2, inplace=False):
    result = dict1 if inplace else dict1.copy()
    result.update(dict2)
    return result


def set_ru_locale():
    import locale

    try:
        locale.setlocale(locale.LC_ALL, 'ru_RU.utf8')
    except Exception as e:
        msg = '<b style="color : red;">!!!!! --- set_ru_locale exception error={0}<br>{1}</b>'.format(
            str(e),
            str(e.args)
        )
        print(msg)
        techSendMail(msg, 'set_ru_locale')
        return False

    return True


def get_all_videos_from_html_content(html):
    if not html:
        return None

    res = re.findall('iframe.*src=\"(.+?)\"', html)

    return res


def get_all_photos_from_html_content(html):
    res = re.findall('src=\"(.+?)\"', html)
    return res


def get_choices_value_by_choices_id(choices, id):
    for ch_id, ch_val in choices:
        if ch_id == id:
            return ch_val

    return None


def sortByLength(inputStr):
    return len(inputStr)


def get_current_language(request):
    return request.LANGUAGE_CODE


def cut_to_number_w_point(string):
    import re

    if not string:
        return string

    string = string.replace(',', '.')
    # str_list = string.split(',')
    #
    # if len(str_list) > 1:
    #     string = str_list[0]
    # else:
    #     str_list = string.split('.')
    # if len(str_list) > 2:
    #     string = u'{0}.{1}'.format(str_list[0], str_list[1])

    try:
        # шаблон для обрезки до цифр
        p = '[0-9]+.[0-9]+'
        number = u''.join(re.findall(p, string))
        if number == u'':
            p = '[0-9]+'
            number = u''.join(re.findall(p, string))
    except:
        number = None
    return number


def cut_to_number(string):
    import re

    if not string:
        return string

    # шаблон для обрезки до цифр
    p = '[\d]+'
    number = ''.join(re.findall(p, string))
    return number


def range_dates(start, end):
    """ Returns the date range """
    from datetime import timedelta

    list = [start + timedelta(days=days) for days in range(0, (end - start).days + 1)]
    return list

    # assert start <= end
    # current = start.year * 12 + start.month - 1
    # end = end.year * 12 + end.month - 1
    # list = []
    # while current <= end:
    #     yield date(current // 12, current % 12 + 1, 1)
    #     current += 1


# разбираем csv строку, получаем Dict
def get_Dict_from_csv_data(csv_data):
    data = {}
    for item in csv_data.split(';'):
        try:
            if item:
                data.update(dict([item.split(':')[0:2]]))
        except ValueError:
            continue

    return data
    # return dict([item.split(':')[0:2] for item in csv_data.split(';') if item])


def cut_url_toPageName(url):
    pageName = url.split('/')[-1]  # получаем урл страницы
    return pageName


def jsonify():
    def decorator(func):
        def wrapper(request, *args, **kwargs):
            result = func(request, *args, **kwargs)
            return HttpResponse(json.dumps(result), mimetype='application/json')

        return wrapper

    return decorator


def check_perms_for_view_order(request, order):
    def decorator(func):
        def wrapper(request, *args, **kwargs):
            c_user = request.user
            if order:
                if c_user == order.user or c_user == order.forUser:
                    return True
                else:
                    if c_user.has_perm('OrdersApp.can_see_orders_all_companys'):
                        return True
                    else:
                        if order.group == c_user.group and c_user.has_perm('OrdersApp.can_see_orders_self_company'):
                            return True

        return wrapper

    return decorator
