# -*- coding: utf-8 -*-
##############################################################################
#
#    datenpol gmbh
#    Copyright (C) 2013-TODAY datenpol gmbh ()
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see .
#
##############################################################################
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
class Partner(models.Model):
    _name = 'res.partner'
    _inherit = ['res.partner', 'dp_custom.helper']
    lastname2 = fields.Char(string='Midname')
    company = fields.Char(string='Unternehmen')
    info_kundennr = fields.Char(string='Info-Kundennr.')
    info_uid = fields.Char(string='Info-UID')
    endkunde = fields.Boolean(string='Endkunde', help='Beschreibt, ob es ein Endkunde ist')
    line_ids = fields.Many2many(comodel_name='res.line', string='Produktionslinien')
    portal_id = fields.Char(string='Portal-ID')
    partner_sector_id = fields.Many2one(comodel_name='res.partner.sector', string='Branche')
    dat_vat_check = fields.Date(string='Datum letzte UID-Prüfung')
    active = fields.Boolean(track_visibility='onchange')
    _sql_constraints = [
        ('ref_uniq', 'unique(ref)', 'Die Interne Referenz muss eindeutig sein')
    ]
    @api.model
    def portal_create_partner(self, vals):
        vals = self.remove_not_specified_fields(vals)
        vals = self.correct_values(vals)
        if not vals.get('active', False):
            vals['active'] = False
        return self.create(vals)
    @api.model
    def pg_create_company(self, vals):
        vals = self.remove_not_specified_fields(vals)
        vals = self.correct_values(vals)
        partner = self.with_context(active_test=False).search([('ref', '=', vals['ref'])])
        if partner:
            if not partner.is_company:
                raise ValidationError(_("Der Partner mit der Internen Referenz '%s' ist kein Unternehmen" % vals['ref']))
            partner = self.write(vals)
        else:
            if not vals.get('is_company', False):
                vals['is_company'] = True
            partner = self.create(vals)
            partner.property_account_fiscal_position = self.env['account.fiscal.position'].get_fiscal_position(
                partner.id)
        return partner
    @api.model
    def correct_values(self, vals):
        if vals.get('country_id', False):
            country = self.env['res.country'].search([('code', '=', vals['country_id'])])
            if country:
                vals['country_id'] = country.id
            else:
                raise ValidationError(
                    _("Das Land mit dem ISO-Code \'%s\' kann nicht zugeordnet werden" % vals['country_id']))
        if vals.get('line_ids', False):
            line_ids = self.env['res.line'].search([('name', 'in', vals['line_ids'])])
            if line_ids:
                vals['line_ids'] = [(6, 0, line_ids.ids)]
            else:
                raise ValidationError(
                    _("Die Produktionslinie mit dem Code \'%s\' kann nicht zugeordnet werden", vals['line_ids']))
        if vals.get('lang', False):
            temp = vals['lang']
            vals['lang'] = False
            for selection in self.fields_get('lang')['lang']['selection']:
                if selection[0].startswith(temp):
                    vals['lang'] = selection[0]
                    break
            if not vals['lang']:
                raise ValidationError(_("Die Sprache mit dem Code \'%s\' kann nicht zugeordnet werden" % temp))
        if vals.get('partner_sector_id', False):
            branche = self.env['res.partner.sector'].search(
                [('name', '=', vals['partner_sector_id'])])
            if branche:
                vals['partner_sector_id'] = branche.id
            else:
                raise ValidationError(_("Die Branche \'%s\' kann nicht zugeordnet werden" % vals['partner_sector_id']))
        return vals
    @api.model
    def _get_specified_fields(self):
        return ['name', 'firstname', 'lastname', 'street', 'street2', 'zip', 'city', 'country_id', 'tax', 'phone', 'mobile',
                'endkunde', 'line_ids', 'lang', 'portal_id', 'email', 'opt_out', 'ref',
                'partner_sector_id', 'comment', 'vat', 'property_payment_term_id',
                'property_pricelist_id', 'date_vat_check', 'active']
class PartnerSector(models.Model):
    _name = 'res.partner.sector'
    _description = 'Branche'
    _order = 'id,name'
    name = fields.Char(string='Beteichnung', required=True)
    sequence = fields.Integer(string='Sequenz')
    _sql_constraints = [
        ('name_uniq', 'unique(name)', 'Die Bezeichnung muss eindeutig sein')
    ]