# -*- coding: utf-8 -*-
# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
"""
Miscelleanous tools used by tryton
"""
import importlib
import io
import math
import os
import re
import types
import unicodedata
import warnings
from collections.abc import Iterable, Sized
from functools import cache, wraps
from itertools import chain, islice, tee, zip_longest

from sql import As, Cast, Select
from sql.conditionals import Case

from trytond.const import MODULES_GROUP, OPERATORS

try:
    from backports.entry_points_selectable import entry_points as _entry_points
except ImportError:
    from importlib.metadata import entry_points as _entry_points


@cache
def entry_points():
    return _entry_points()


def import_module(name):
    try:
        ep, = entry_points().select(group=MODULES_GROUP, name=name)
    except ValueError:
        return importlib.import_module(f'{MODULES_GROUP}.{name}')
    return ep.load()


def file_open(name, mode="r", subdir='modules', encoding=None):
    "Open a file from the root directory, using subdir folder"
    path = find_path(name, subdir, _test=None)
    return io.open(path, mode, encoding=encoding)


_root_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


@cache
def find_path(name, subdir='modules', _test=os.path.isfile):
    "Return path from the root directory, using subdir folder"

    def secure_join(root, *paths):
        "Join paths and ensure it still below root"
        path = os.path.join(root, *paths)
        path = os.path.normpath(path)
        if not path.startswith(os.path.join(root, '')):
            raise IOError("Permission denied: %s" % name)
        return path

    if subdir:
        if subdir == 'modules':
            try:
                module_name, module_path = name.split(os.sep, 1)
            except ValueError:
                module_name, module_path = name, ''
            if module_name in {'ir', 'res', 'tests'}:
                path = secure_join(_root_path, module_name, module_path)
            else:
                try:
                    module = import_module(module_name)
                except ModuleNotFoundError:
                    path = secure_join(_root_path, subdir, name)
                else:
                    path = os.path.dirname(module.__file__)
                    if module_path:
                        path = secure_join(path, module_path)
        else:
            path = secure_join(_root_path, subdir, name)
    else:
        path = secure_join(_root_path, name)

    if not _test or _test(path):
        return path
    else:
        raise FileNotFoundError("No such file or directory: %r" % name)


def find_dir(name, subdir='modules'):
    "Return directory from the root directory, using subdir folder"
    return find_path(name, subdir=subdir, _test=os.path.isdir)


def get_smtp_server():
    """
    Instanciate, configure and return a SMTP or SMTP_SSL instance from
    smtplib.
    :return: A SMTP instance. The quit() method must be call when all
    the calls to sendmail() have been made.
    """
    from trytond.sendmail import get_smtp_server
    warnings.warn(
        'get_smtp_server is deprecated use trytond.sendmail',
        DeprecationWarning)
    return get_smtp_server()


def reduce_ids(field, ids):
    from trytond.model.fields import SQL_OPERATORS
    warnings.warn(
        "reduce_ids is deprecated use trytond.fields.SQL_OPERATORS['in']",
        DeprecationWarning)
    return SQL_OPERATORS['in'](field, ids)


def reduce_domain(domain):
    '''
    Reduce domain
    '''
    if not domain:
        return []
    operator = 'AND'
    if isinstance(domain[0], str):
        operator = domain[0]
        domain = domain[1:]
    result = [operator]
    for arg in domain:
        if (isinstance(arg, tuple)
                or (isinstance(arg, list)
                    and len(arg) > 2
                    and arg[1] in OPERATORS)):
            # clause
            result.append(arg)
        elif isinstance(arg, list) and arg:
            # sub-domain
            sub_domain = reduce_domain(arg)
            sub_operator = sub_domain[0]
            if sub_operator == operator:
                result.extend(sub_domain[1:])
            else:
                result.append(sub_domain)
        else:
            result.append(arg)
    return result


def grouped_slice(records, count=None):
    'Grouped slice'
    if count is None:
        warnings.warn(
            "grouped_slice without size is deprecated",
            DeprecationWarning)
        count = 1
    count = max(1, count)
    if not isinstance(records, Sized):
        records = list(records)
    for i in range(0, len(records), count):
        yield islice(records, i, i + count)


def pairwise_longest(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip_longest(a, b)


def is_instance_method(cls, method):
    for klass in cls.__mro__:
        type_ = klass.__dict__.get(method)
        if type_ is not None:
            return isinstance(type_, types.FunctionType)


def resolve(name):
    "Resolve a dotted name to a global object."
    name = name.split('.')
    used = name.pop(0)
    found = importlib.import_module(used)
    for n in name:
        used = used + '.' + n
        try:
            found = getattr(found, n)
        except AttributeError:
            found = importlib.import_module(used)
    return found


def strip_wildcard(string, wildcard='%', escape='\\'):
    "Strip starting and ending wildcard from string"
    string = lstrip_wildcard(string, wildcard)
    return rstrip_wildcard(string, wildcard, escape)


def lstrip_wildcard(string, wildcard='%'):
    "Strip starting wildcard from string"
    if string and string.startswith(wildcard):
        string = string[1:]
    return string


def rstrip_wildcard(string, wildcard='%', escape='\\'):
    "Strip ending wildcard from string"
    if (string
            and string.endswith(wildcard)
            and not string.endswith(escape + wildcard)):
        string = string[:-1]
    return string


def escape_wildcard(string, wildcards='%_', escape='\\'):
    for wildcard in escape + wildcards:
        string = string.replace(wildcard, escape + wildcard)
    return string


def unescape_wildcard(string, wildcards='%_', escape='\\'):
    for wildcard in wildcards + escape:
        string = string.replace(escape + wildcard, wildcard)
    return string


def is_full_text(value, escape='\\'):
    if not value:
        return False
    escaped = strip_wildcard(value, escape=escape)
    escaped = escaped.replace(escape + '%', '').replace(escape + '_', '')
    if '%' in escaped or '_' in escaped:
        return False
    return value.startswith('%') == value.endswith('%')


def likify(string, escape='\\'):
    if not string:
        return '%'
    escaped = string.replace(escape + '%', '').replace(escape + '_', '')
    if '%' in escaped or '_' in escaped:
        return string
    else:
        return '%' + string + '%'


_slugify_strip_re = re.compile(r'[^\w\s-]')
_slugify_hyphenate_re = re.compile(r'[-\s]+')


def slugify(value, hyphenate='-'):
    if not isinstance(value, str):
        value = str(value)
    value = unicodedata.normalize('NFKD', value)
    value = str(_slugify_strip_re.sub('', value).strip())
    return _slugify_hyphenate_re.sub(hyphenate, value)


def sortable_values(func):
    "Decorator that makes list of values sortable"
    @wraps(func)
    def wrapper(*args, **kwargs):
        result = list(func(*args, **kwargs))
        for i, value in enumerate(list(result)):
            if not isinstance(value, Iterable):
                value = [value]
            result[i] = tuple(chain((k is None, k) for k in value))
        return result
    return wrapper


def sql_pairing(x, y):
    """Return SQL expression to pair x and y
    Pairing function from http://szudzik.com/ElegantPairing.pdf"""
    x = Cast(x, 'BIGINT')
    y = Cast(y, 'BIGINT')
    return Cast(Case(
            (x < y, (y * y) + x),
            else_=(x * x) + x + y), 'BIGINT')


def pair(x, y):
    "Returns z as a pair of x and y"
    if x < 0 or y < 0:
        raise ValueError("x and y must be non-negative")
    if x < y:
        z = y ** 2 + x
    else:
        z = x ** 2 + x + y
    return z


def unpair(z):
    "Returns the x and y pair associated with z"
    if z < 0:
        raise ValueError("z must be non-negative")
    sqrtz = math.isqrt(z)
    sq = sqrtz ** 2
    if z - sq < sqrtz:
        x = z - sq
        y = sqrtz
    else:
        x = sqrtz
        y = z - sq - sqrtz
    return x, y


def sqlite_apply_types(select, types):
    "Apply SQLite types to column names of the select query"
    assert isinstance(select, Select)
    for column, type in zip(select.columns, types):
        if type:
            assert isinstance(column, As)
            column.output_name += ' [%s]' % type


def firstline(text):
    "Returns first non-empty line"
    try:
        return next((x for x in text.splitlines() if x.strip()))
    except StopIteration:
        return ''


def remove_forbidden_chars(value):
    from trytond.model.fields import Char
    if value is None:
        return value
    for c in Char.forbidden_chars:
        if c in value:
            value = value.replace(c, ' ')
    return value.strip()
