##############################################################################
#
#    Copyright (C) 2016 Compassion CH (http://www.compassion.ch)
#    Releasing children from poverty in Jesus' namenoupdate="1"
#    @author: Emanuel Cino <ecino@compassion.ch>
#
#    The licence is in the file __manifest__.py
#
##############################################################################
import re
from datetime import datetime

from babel.dates import format_date

from odoo import api, models, fields, _


class ResPartner(models.Model):
    """ Add fields for retrieving values for communications.

        - Short address
            Mr. John Doe
            Street
            City
            Country
    """

    _name = "res.partner"
    _inherit = "res.partner"

    salutation = fields.Char(compute="_compute_salutation")
    short_salutation = fields.Char(compute="_compute_salutation")
    informal_salutation = fields.Char(compute="_compute_salutation")
    full_salutation = fields.Char(compute="_compute_salutation")
    gender = fields.Selection(related="title.gender", readonly=True)
    thankyou_preference = fields.Selection(
        "_get_delivery_preference", default="auto_digital", required=True
    )
    full_name = fields.Char(compute="_compute_full_name")
    short_address = fields.Char(compute="_compute_address")
    date_communication = fields.Char(compute="_compute_date_communication")

    @api.multi
    def _compute_salutation(self):
        for partner in self:
            lang_partner = partner.with_context(lang=partner.lang)
            if partner.title and partner.firstname and not partner.is_company:
                title = lang_partner.title
                title_salutation = (
                    lang_partner.env["ir.advanced.translation"]
                    .get("salutation", female=title.gender == "F",
                         plural=title.plural)
                    .title()
                )
                title_name = title.name
                partner.salutation = (
                    title_salutation + " " + title_name + " " +
                    lang_partner.lastname
                )
                partner.short_salutation = title_salutation + " " + \
                    lang_partner.firstname
                partner.informal_salutation = title_salutation + " " + \
                    lang_partner.firstname
                partner.full_salutation = (
                    title_salutation + " " + lang_partner.firstname + " " +
                    lang_partner.lastname
                )
            else:
                with api.Environment.manage():
                    # this will enable translation of "Dear friends of Compassion"
                    env = api.Environment(  # noqa: F841
                        self.env.cr, self.env.uid, lang_partner.env.context)
                    partner.salutation = (
                        _("Dear friends of ") + self.env.user.company_id.name
                    )
                    partner.short_salutation = lang_partner.salutation
                    partner.informal_salutation = (
                        _("Dear friend of ") + self.env.user.company_id.name
                    )
                    partner.full_salutation = lang_partner.salutation

    @api.multi
    def _compute_full_name(self):
        for partner in self.filtered("firstname"):
            partner.full_name = partner.firstname + " " + partner.lastname

    @api.multi
    def _compute_address(self):
        # Replace line returns
        p = re.compile("\\n+")
        for partner in self:
            res = ""
            t_partner = partner.with_context(lang=partner.lang)
            if not partner.is_company and partner.title.shortcut:
                res = t_partner.title.shortcut + " "
                if partner.firstname:
                    res += partner.firstname + " "
                res += partner.lastname + "<br/>"
            res += t_partner.contact_address
            partner.short_address = p.sub("<br/>", res)

    @api.multi
    def _compute_date_communication(self):
        """City and date displayed in the top right of a letter"""
        today = datetime.today()
        city = self.env.user.partner_id.company_id.city
        for partner in self:
            date = format_date(today, format="long", locale=partner.lang)
            formatted_date = f"le {date}" if "fr" in partner.lang else date
            partner.date_communication = f"{city}, {formatted_date}"


class ResUsers(models.Model):
    _inherit = "res.users"

    signature_letter = fields.Html(compute="_compute_signature_letter")

    @api.multi
    def _compute_signature_letter(self):
        for user in self:
            employee = user.employee_ids.sudo()
            signature = ""
            if len(employee) == 1:
                signature = employee.name + "<br/>"
                if employee.department_id:
                    signature += employee.department_id.name + "<br/>"
            signature += user.sudo().company_id.name
            user.signature_letter = signature

@@ -831,208 +831,8 @@
 n%22)%0A
-    short_salutation = fields.Char(compute=%22_compute_salutation%22)%0A    informal_salutation = fields.Char(compute=%22_compute_salutation%22)%0A    full_salutation = fields.Char(compute=%22_compute_salutation%22)%0A
     
@@ -1277,174 +1277,114 @@
     
-for partner in self:%0A            lang_partner = partner.with_context(lang=partner.lang)%0A            if partner.title and partner.firstname and not partner.is_company:
+%22%22%22 Define a method _get_salutation_%3Clang_code%3E for using a specific salutation based on partner language.
 %0A   
@@ -1384,32 +1384,36 @@
 ge.%0A        
+%22%22%22%0A
         
 title = lang
@@ -1404,74 +1404,29 @@
     
-title = lang_partner.title%0A                title_salutation = (%0A  
+for partner in self:%0A
     
@@ -1425,38 +1425,32 @@
 lf:%0A            
-      
 lang_partner.env
@@ -1449,402 +1449,123 @@
 tner
-.env%5B%22ir.advanced.translation%22%5D%0A                    .get(%22salutation%22, female=title.gender == %22F%22,%0A                         plural=title.plural)%0A                    .title()%0A                )%0A                title_name = title.name%0A                partner.salutation = (%0A                    title_salutation + %22 %22 + title_name + %22 %22 +%0A                    lang_partner.lastname%0A                )
+ = partner.with_context(lang=partner.lang)%0A            if hasattr(lang_partner, %22_get_salutation_%22 + partner.lang):
 %0A   
@@ -1577,38 +1577,32 @@
         partner.
-short_
 salutation = tit
@@ -1602,193 +1602,84 @@
 n = 
-title_salutation + %22 %22 + %5C%0A                    lang_partner.firstname%0A                partner.informal_salutation = title_salutation + %22 %22 + %5C%0A                    lang_partner.firstname
+getattr(lang_partner, %22_get_salutation_%22 + partner.lang)()%0A            else:
 %0A   
@@ -1691,37 +1691,32 @@
         partner.
-full_
 salutation = (%0A 
@@ -1716,720 +1716,213 @@
 n = 
-(%0A                    title_salutation + %22 %22 + lang_partner.firstname + %22 %22 +%0A                    lang_partner.lastname%0A                )%0A            else:%0A                with api.Environment.manage():%0A                    # this will enable translation of %22Dear friends of Compassion%22%0A                    env = api.Environment(  # noqa: F841%0A                        self.env.cr, self.env.uid, lang_partner.env.context)%0A                    partner.salutation = (%0A                        _(%22Dear friends of %22) + self.env.user.company_id.name%0A                    )%0A                    partner.short_salutation = lang_partner.salutation%0A                    partner.informal_salutation = (%0A                        _(
+lang_partner._get_salutation_en_US()%0A%0A    def _get_salutation_en_US(self):%0A        self.ensure_one()%0A        if self.firstname:%0A            return %22Dear %22 + self.firstname%0A        else:%0A            return 
 %22Dea
@@ -1933,138 +1933,24 @@
 iend
+s
  of 
-%22) + self.env.user.company_id.name%0A                    )%0A                    partner.full_salutation = lang_partner.salutat
+Compass
 ion
+%22
 %0A%0A  

Change salutation fields