import os
import polib
import peewee
from common.models import WebLang, WebForm, WebMenu, WebMenuTranslation
from common.util import logger
import time

locales_dir = os.path.join(os.path.dirname(__file__), "..", "locales")

availables_locales = ["en", "fr", "it", "pl", "es"]

metadata = {
    "Project-Id-Version": "1.0",
    "Report-Msgid-Bugs-To": "c.chauvet@deenova.com",
    "POT-Creation-Date": "2007-10-18 14:00+0100",
    "PO-Revision-Date": time.strftime("%Y-%m-%d %H:%M") + "+0100",
    "Last-Translator": "Christophe CHAUVET <c.chauvet@deenova.com>",
    "Language-Team": "English <yourteam@example.com>",
    "MIME-Version": "1.0",
    "Content-Type": "text/plain; charset=utf-8",
    "Content-Transfer-Encoding": "8bit",
}


def export_menu():
    return True


def delete_i18n_lang(langcode: str) -> bool:
    try:
        # lng = WebLang.get(WebLang.iso_639_code == langcode)
        lngs = WebLang.select(WebLang).where(WebLang.iso_639_code == langcode)
        for lng in lngs:
            print("-> Delete Regional menu: %s" % lng.code)
            WebMenuTranslation().delete().where(WebMenuTranslation.lang_id == lng.pk).execute()
    except peewee.DoesNotExist:
        # Lang does not exists in the database, we continue
        print("Lang not exists in the database %s" % langcode)

    try:
        lngs = WebLang.select(WebLang).where(WebLang.iso_639_code == langcode)
        for lng in lngs:
            print("-> Delete Regional form: %s" % lng.code)
            WebForm().delete().where(WebForm.lang_id == lng.pk).execute()
    except peewee.DoesNotExist:
        # Lang does not exists in the database, we continue
        print("Lang not exists in the database %s" % langcode)

    return True


def menu_i18n_file_import(fname, langcode: str = None) -> bool:
    """Read a PO file and import it on the database"""
    try:
        i18n_file = polib.pofile(fname)
    except OSError:
        logger.warning("File %s for lang %s not found" % (fname, langcode))
        return False

    try:
        lngs = WebLang.select(WebLang).where(WebLang.iso_639_code == langcode)
    except peewee.DoesNotExist:
        # Lang does not exists in the database, we continue
        print("Lang not exists in the database %s" % langcode)
        return False
    for lng in lngs:
        print("-> Regional menu: %s" % lng.code)
        for entry in i18n_file:
            try:
                mnu = WebMenu.get(WebMenu.code == entry.comment)
            except peewee.DoesNotExist:
                logger.warning("Menu %s not found in the database" % (entry.comment,))
                continue

            tr_name = entry.msgstr
            if not entry.msgstr:
                tr_name = entry.msgid
            try:
                mnu_i18n = WebMenuTranslation()
                mnu_i18n.menu_id = mnu
                mnu_i18n.lang_id = lng
                mnu_i18n.tr_name = tr_name
                mnu_i18n.save()
            except peewee.IntegrityError:
                mnu_i18n = WebMenu.get(WebMenu.code == entry.comment)
                mnu_i18n.tr_name = tr_name
                mnu_i18n.save()

    return True


def form_i18n_file_import(fname, langcode=None):
    """Read a PO file and import it on the database"""
    i18n_file = polib.pofile(fname)
    lngs = WebLang.select(WebLang).where(WebLang.iso_639_code == langcode)
    for lng in lngs:
        print("-> Regional form: %s" % lng.code)
        for entry in i18n_file:
            tr_name = entry.msgstr
            if not entry.msgstr:
                tr_name = entry.msgid
            for occ in entry.occurrences:
                key = occ[0]
                try:
                    frm_i18n = WebForm()
                    frm_i18n.key = key
                    frm_i18n.lang_id = lng
                    frm_i18n.tr_name = tr_name
                    frm_i18n.save()
                except peewee.IntegrityError:
                    frm_i18n = WebForm.get(WebForm.key == key, WebForm.lang_id == lng)
                    frm_i18n.tr_name = tr_name
                    frm_i18n.save()

    return True


def form_18n_to_json(langcode):
    """Export translation from the database"""
    res = {}
    try:
        lng = WebLang.get(WebLang.iso_639_code == langcode)
        for term in WebForm.select().where(WebForm.lang_id == lng):
            res[term.key] = term.tr_name
    except peewee.DoesNotExist:
        pass
    return res


def convert_pot2po(pofile, potfile):
    """Merge catalog in the pofile"""
    logger.debug(pofile)
    logger.debug(potfile)
    if not os.path.exists(pofile):
        po = polib.POFile()
        po.metadata = metadata
        po.save(pofile)

    try:
        po = polib.pofile(pofile)
        pot = polib.pofile(potfile)
        po.merge(pot)
        po.save(pofile)
        return True
    except OSError:
        logger.warning("File %s not found" % (pofile,))
        return False


def clean_pot2po(pofile):
    if not os.path.exists(pofile):
        return False

    po_new = polib.POFile()
    po_new.metadata = metadata

    po = polib.pofile(pofile)
    for entry in po:
        # print(entry.occurrences)
        add_entry = True
        for occ in entry.occurrences:
            if occ[0].startswith("web_form"):
                add_entry = False

        if add_entry:
            po_new.append(entry)

    po_new.save(pofile)
