# -*- coding: utf-8 -*-
"""I18n tools."""

__copyright__ = "Copyright 2019, 3Liz"
__license__ = "GPL version 3"
__email__ = "info@3liz.org"
__revision__ = "$Format:%H$"

# -----------------------------------------------------------
# Copyright (C) 2019 3Liz
# -----------------------------------------------------------
# Licensed under the terms of GNU GPL 3
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# ---------------------------------------------------------------------

from os.path import join

from qgis.core import QgsSettings
from qgis.PyQt.QtCore import QFileInfo, QLocale
from qgis.PyQt.QtWidgets import QApplication

from geest.utilities import resources_path


def setup_translation(file_pattern="{}.qm", folder=None):
    """Find the translation file according to locale.

    Args:
        file_pattern: Custom file pattern to use to find QM files.
        folder: Optional folder to look in if it's not the default.

    Returns:
        tuple: The locale and the file path to the QM file, or None.
    """
    locale = QgsSettings().value("locale/userLocale", QLocale().name())

    if folder:
        ts_file = QFileInfo(join(folder, file_pattern.format(locale)))
    else:
        ts_file = QFileInfo(resources_path("i18n", file_pattern.format(locale)))
    if ts_file.exists():
        return locale, ts_file.absoluteFilePath()

    if folder:
        ts_file = QFileInfo(join(folder, file_pattern.format(locale[0:2])))
    else:
        ts_file = QFileInfo(resources_path("i18n", file_pattern.format(locale[0:2])))
    if ts_file.exists():
        return locale, ts_file.absoluteFilePath()

    return locale, None


def tr(text, context="@default"):
    """🔄 Tr.

    Args:
        text: Text.
        context: Context.

    Returns:
        The result of the operation.
    """
    return QApplication.translate(context, text)
