# -*- coding: utf-8 -*-
###############################################################################
#
#    Tech-Receptives Solutions Pvt. Ltd.
#    Copyright (C) 2009-TODAY Tech-Receptives(<http://www.techreceptives.com>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Lesser 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 Lesser General Public License for more details.
#
#    You should have received a copy of the GNU Lesser General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################

from odoo.osv import expression
from odoo.tools.float_utils import float_round as round
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT
from odoo.exceptions import UserError, ValidationError
from odoo import api, fields, models, _

@api.model
def _lang_get(self):
    languages = self.env['res.lang'].search([])
    return [(language.code, language.name) for language in languages]
	
class EcomEbusiness(models.Model):
    _name = 'ecom.ebusiness'
    _inherits = {'res.partner': 'partner_id'}
    _inherit = ['ir.needaction_mixin', 'mail.thread']
    _description = "Ebusiness"

    #JCF - 31-03-2017
    @api.one
    @api.depends('contacts_line')
    def _get_ebusiness_id(self):
        ebusiness_email=''
        count=0
        if self.contacts_line:
            for contact in self.contacts_line:
                if contact.send_email is True and contact.partner_id.email:
                    if count==0:
                        ebusiness_email=contact.partner_id.email
                    else:
                        ebusiness_email=ebusiness_email + ';' + contact.partner_id.email
                    count=count+1
                else:
                    if contact.send_email is True and not contact.email:
                        raise ValidationError('The selected contact does not have an email configured. Please add the email to the selected contact.')
        self.ebusiness_email=ebusiness_email

    @api.one
    @api.depends('partner_id')
    def _get_contracts(self):
        cont=0
        partner_id=self.partner_id.id
        ebusiness_id=False
        self._cr.execute("""select id from ecom_ebusiness where partner_id=%s"""%(partner_id))
        result = self._cr.fetchone()
        if result:
            ebusiness_id = result[0]
        self._cr.execute("""select count(*) as cont from ecom_ebusiness_contract_rel c where c.ebusiness_id=%s"""%(ebusiness_id))
        result2 = self._cr.fetchone()
        if result2:
            cont = result2[0]
        if cont > 0:
            self.has_contract = True
        else:
            self.has_contract=False

    @api.model
    def _get_euro(self):
        return self.env['res.currency.rate'].search([('rate', '=', 1)], limit=1).currency_id

    @api.model
    def _get_user_currency(self):
        currency_id = self.env['res.users'].browse(self._uid).company_id.currency_id
        return currency_id or self._get_euro()

    active = fields.Boolean('Is Active?', default=True)
    logo = fields.Binary('Logo', track_visibility='onchange')
    photo = fields.Binary('Photo', track_visibility='onchange')
    lang = fields.Selection(_lang_get, 'Language', default='pt_PT', track_visibility='onchange')
    partner_id = fields.Many2one(
        'res.partner', 'Partner', required=True, ondelete="cascade", track_visibility='onchange',index=True)

    user_id = fields.Many2one('res.users', 'Related User')

    country_id = fields.Many2one('ecom.location', 'Country', track_visibility='onchange',index=True)
    island_id = fields.Many2one('ecom.location', 'Island', track_visibility='onchange',index=True)
    county_id = fields.Many2one('ecom.location', 'County', track_visibility='onchange',index=True)
    parish_id = fields.Many2one('ecom.location', 'Parish', track_visibility='onchange',index=True)
    local_id = fields.Many2one('ecom.location', 'Local', track_visibility='onchange',index=True)
    neighborhood_id = fields.Many2one('ecom.location', 'Neighborhood', track_visibility='onchange',index=True)
    state = fields.Selection([('draft', 'New'),
                              ('conceived', 'Conceived'),
                              ('approved', 'Approved'),
                              ('mounted', 'Mounted'),
                              ('inserted', 'Inserted'),('online', 'Online'),('cancel', 'Cancelled')], 'State', default='draft', track_visibility='onchange',translate=False,index=True)
    ebusiness_type_id = fields.Many2one('ecom.ebusiness.type', 'Ebusiness type',index=True)
    customer_id = fields.Many2one('ecom.customer', 'Customer',index=True)
    published = fields.Boolean('Published', default=False,index=True)
    online = fields.Boolean('Online', default=False)
    #Services tab
    one_page = fields.Boolean('One Page', default=False)
    has_site = fields.Boolean('Has site', default=False)
    site = fields.Char(string='Site')
    domain_registered = fields.Boolean('Has a registered domain?', default=False)
    domain = fields.Char(string='Domain')
    domain_test = fields.Char(string='Domain Test')
    domain_production = fields.Char(string='Domain Production')
    date_online = fields.Date(string='Date Online')
    #Safepay tab
    pos_id = fields.Char(string='ID Terminal 24')
    posautcode = fields.Char(string='ID customer')
    url_sisp = fields.Char(string='SISP URL')
    url_response = fields.Char(string='URL Response')
    nif = fields.Integer(string='NIF')
    account_number = fields.Char(string='Account Number')
    business_registration = fields.Char(string='Business Registration')
    has_online_payment = fields.Boolean('Has another service other than safePay.prime.cv?', default=False)
    #Contracts tab
    contract_ebusiness_ids = fields.Many2many('ecom.contract', 'ecom_ebusiness_contract_rel', 'ebusiness_id', 'contract_id', string='Contracts', copy=False)
    #Color
    color = fields.Integer(string='Color', default=1)
    captcha_key = fields.Char(string='Captcha Key')
    ebusiness_email = fields.Char(string='Ebusiness email', compute='_get_ebusiness_id', store=True)
    has_contract = fields.Boolean(string='Has contract', compute='_get_contracts', store=True)
    contacts_line = fields.One2many('ecom.ebusiness.contact', 'ebusiness_id', 'Contacts')
    api_key = fields.Char(string='API Key')
    #JCF - 09-02-2018
    our_site = fields.Boolean('Our site', default=False)
    #JCF 08-03-2018
    featured = fields.Integer('Featured', default=0)
    #JCF 09-04-2018
    currency_id = fields.Many2one('res.currency', string='Currency', required=True, default=lambda self: self._get_user_currency())
    #JCF 27-05-2018
    company_id = fields.Many2one('res.company', string='Company', required=True)

    @api.multi
    def action_draft(self):
        return self.write({'state': 'draft','color':2})

    @api.multi
    def action_conceived(self):
        return self.write({'state': 'conceived','color':1})

    @api.multi
    def action_approved(self):
        return self.write({'state': 'approved','color':7})

    @api.multi
    def action_mounted(self):
        return self.write({'state': 'mounted','color':1})

    @api.multi
    def action_inserted(self):
        return self.write({'state': 'inserted','color':3})

    @api.multi
    def action_online(self):
        return self.write({'state': 'online','color':5,'published':True})

    @api.multi
    def action_cancel(self):
        return self.write({'state': 'cancel','color':4,'published':False,'date_online':None})

    @api.multi
    def action_assign_contacts(self):
        """Assign contacts
        """
        ebusiness_ids = self.env['ecom.ebusiness'].search([('id','>',0)])
        for ebusiness in ebusiness_ids:
            ebusiness_id=ebusiness.id
            e_id=ebusiness.ebusiness_id
            partner_ids = self.env['res.partner'].search([('ebusiness_id','=',e_id)])
            
            for partner in partner_ids:
                partner_id=partner.id
                self._cr.execute("""INSERT INTO ecom_ebusiness_contact_rel (ebusiness_id,contact_id) VALUES (%s,%s)"""%(ebusiness_id,partner_id))

    @api.multi
    def action_assign_contacts2(self):
        """Assign contacts to one2many relation
        """
        ebusiness_ids = self.env['ecom.ebusiness'].search([('id','>',0)])
        for ebusiness in ebusiness_ids:
            lst = []
            ebusiness_id=ebusiness.id
            self._cr.execute("""select contact_id from ecom_ebusiness_contact_rel c where c.ebusiness_id=%s"""%(ebusiness_id))
            result = self._cr.fetchall()
            if result:
                for res in result:
                    lst.append(res[0])

            partner_ids = self.env['res.partner'].search([('id','in',lst)])
            
            for partner in partner_ids:
                partner_id=partner.id
                self.env['ecom.ebusiness.contact'].create({
                    'partner_id': partner_id,
                    'ebusiness_id': ebusiness_id,
                    'default_contact': partner.default_contact,
                    'send_email':partner.send_email,
                    'email': partner.email,
                    'phone': partner.phone,
                    'mobile': partner.mobile,
                    'nif': partner.nif,
                    'id_number': partner.id_number,
                })

    @api.multi
    def action_update_has_contract(self):
        has_contract=False
        ebusinesses = self.env['ecom.ebusiness'].search([])

        for ebusiness in ebusinesses:
            if ebusiness.contract_ebusiness_ids:
                has_contract = True
            else:
                has_contract=False
            ebusiness.write({'has_contract':has_contract})

    @api.model_cr
    def init(self):
        cr = self._cr
        cr.execute("""
CREATE OR REPLACE FUNCTION date_online(integer)
	RETURNS integer AS
$BODY$ declare

	v_num_records integer :=0; 	         
begin

	select count(*) into v_num_records from ecom_contract c, ecom_ebusiness_contract_rel cb, ecom_ebusiness e where cb.contract_id=c.id and cb.ebusiness_id=e.id and cb.ebusiness_id=$1 and (c.end_date is null or c.end_date >= now()) and e.date_online < now();
	
	return v_num_records;
end;$BODY$
LANGUAGE plpgsql VOLATILE
            """)

class ResPartner(models.Model):
    _inherit = ['res.partner']

    nif = fields.Integer(string='NIF')
    id_number = fields.Char(string='ID Number')
    default_contact = fields.Boolean(string='Default contact', default=False)
    ebusiness_id = fields.Integer(string='Ebusiness ID')
    send_email = fields.Boolean(string='Send email', default=False)
    is_guest = fields.Boolean(string='Is guest', default=False)


class EcomEbusinessContact(models.Model):
    _name = 'ecom.ebusiness.contact'
    _rec_name = 'ebusiness_id'
    _order = "ebusiness_id"
		

    ebusiness_id = fields.Many2one('ecom.ebusiness', 'Ebusiness')
    partner_id = fields.Many2one('res.partner', 'Contact', required=True)
    default_contact = fields.Boolean(string='Default contact', default=False)
    send_email = fields.Boolean(string='Send email', default=False)
    nif = fields.Integer(string='NIF')
    id_number = fields.Char(string='ID Number')
    email = fields.Char(string='Email')
    phone = fields.Char(string='Phone')
    mobile = fields.Char(string='Mobile')
    email_copy = fields.Char(string='Email Copy')
    phone_copy = fields.Char(string='Phone Copy')
    mobile_copy = fields.Char(string='Mobile Copy')
    email_partner = fields.Char(string='Email partner')
    address = fields.Char(string='Address')

    @api.onchange('partner_id')
    def _onchange_partner(self):
        if self.partner_id:
            email_temp = self.email
            self.phone = self.partner_id.phone
            self.mobile = self.partner_id.mobile
            if self.email_partner and self.partner_id.email:
                self.email = email_temp.replace(self.email_partner,self.partner_id.email)
            else:
                self.email = self.partner_id.email
            self.email_partner = self.partner_id.email

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
