# _*_ coding: utf-8 _*_
from odoo import models, fields, api
from odoo.exceptions import UserError

class JptipEventPlan(models.Model):
    _inherit = 'event.plan'

    @api.model
    def create(self, vals):
        res = super(JptipEventPlan, self).create(vals)
        event_id = self.env['jptip.event'].search([('name', '=', res.name), ('event_date', '=', res.x_datetime), ('company_id', '=', res.event_company.id)])
        if not event_id:
            self.env['jptip.event'].create({
                'name': res.name,
                'event_description': res.event_description or False,
                'event_date': res.x_datetime,
                'event_class_room': res.event_class_room.id or False,
                'event_teacher': res.event_teacher.id or False,
                'state': 'draft',
                'company_id': res.event_company.id,
                'jptip_event_id': res.id
            })
        return res

    @api.multi
    def write(self, vals):
        res = super(JptipEventPlan, self).write(vals)
        event_id = self.env['jptip.event'].search([('name','=',self.name),('event_date','=',self.x_datetime),('company_id','=',self.event_company.id)],limit=1)
        if event_id:
            sql = 'UPDATE jptip_event SET name = a.name, event_description = a.event_description, event_date = a.x_datetime, event_class_room = a.event_class_room, event_teacher = a.event_teacher, company_id = a.event_company FROM event_plan a WHERE a.id = %s AND jptip_event.id = %s' % (self.id, event_id.id)
            self._cr.execute(sql)
        return res


class JptipEvent(models.Model):
    _inherit = 'jptip.event'

    @api.multi
    def write(self, vals):
        res = super(JptipEvent, self).write(vals)
        event_id = self.env['event.plan'].search([('name','=',self.name),('event_date','=',self.event_date),('event_company','=',self.company_id.id)],limit=1)
        if event_id:
            sql = 'UPDATE event_plan SET name = a.name, event_description = a.event_description, x_datetime = a.event_date, event_class_room = a.event_class_room, event_teacher = a.event_teacher, event_company = a.company_id FROM jptip_event a WHERE a.id = %s AND event_plan.id = %s' % (self.id, event_id.id)
            self._cr.execute(sql)
        return res