# -*- coding: utf-8 -*-

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, _
from odoo import tools

class EtourismEnterprise(models.Model):

    _inherit = 'etourism.enterprise'
    _description = "Enterprise Directory"

    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/City', track_visibility='onchange',index=True)
    neighborhood_id = fields.Many2one('ecom.location', 'Neighborhood', track_visibility='onchange',index=True)
    type_id = fields.Many2one('ecom.ebusiness.type', 'Ebusiness type',index=True)
    num_employees = fields.Integer('Number of employees')
    directory_state = fields.Selection([('draft', 'Draft'),
                              ('validated', 'Validated'),
                              ('published', 'Published')], 'Enterprise State', default='draft', track_visibility='onchange',translate=False,index=True)
    rooms_types_line = fields.One2many('etourism.directory.enterprise.room', 'enterprise_id', string="Rooms Info")
    amenities_line = fields.One2many('etourism.enterprise.amenity', 'enterprise_id', string="Enterprise Amenities")
    island_code = fields.Char(string='Island Code', related='island_id.code', readonly=True, store=True,index=True)
    contacts_line = fields.One2many('ecom.ebusiness.contact', 'enterprise_id', 'Contacts')
    is_legal = fields.Boolean('Enterprise is legal',default=False)
    ebusiness_type_code = fields.Char(string='Ebusiness Type Code', related='type_id.code', readonly=True, store=True,index=True)
    ebusiness_id = fields.Many2one('ecom.ebusiness', 'Ebusiness', required=False,index=True)

    @api.multi
    def action_draft(self):
        return self.write({'directory_state': 'draft'})

    @api.multi
    def action_validate(self):
        return self.write({'directory_state': 'validated'})

    @api.multi
    def action_publish(self):
        return self.write({'directory_state': 'published'})

    @api.multi
    def toggle_is_legal(self):
        """ Inverse the value of the field ``is_legal`` on the records in ``self``. """
        for record in self:
            record.is_legal = not record.is_legal

    @api.model
    def default_get(self, fields):
        res = super(EtourismEnterprise, self).default_get(fields)
        context = self._context or {}
        #print "DEFAULT GET::::::::::::::::"
        #print context
        if context and 'menu_origin' in context:
            country_id = self.env['ecom.location'].search([('code','=','CV')],limit=1)
            island_id = self.env['ecom.location'].search([('code','=','SV')],limit=1)
            if country_id and island_id:
                res.update({'country_id': country_id.id,'island_id': island_id.id})
        if context and 'menu_accommodation' in context:
            type_id = self.env['ecom.ebusiness.type'].search([('code','=','ALO')],limit=1)
            if type_id:
                res.update({'type_id': type_id.id})
        if context and 'menu_restauration' in context:
            type_id = self.env['ecom.ebusiness.type'].search([('code','=','REST')],limit=1)
            if type_id:
                res.update({'type_id': type_id.id})
        return res

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        context = self._context or {}
        user = context.get('uid', False)
        #print "ENTERPRISE SEARCH:::::::::::::::::::::::::::::::: ",args,offset,limit,order,count
        partner_id = False
        #print "CONTEXT: ", context, self.user_has_groups
        if context and 'menu_origin' in context and (self.user_has_groups('etourism.group_etourism_directory_non_tms_operator') or self.user_has_groups('etourism.group_etourism_directory_tms_operator')):
            user_id = self.env['res.users'].search([('id', '=', user)], limit=1)
            if user_id and user_id.enterprise_id:
                print "FILTER ENTERPRISE_ID: ", user_id.enterprise_id
                args.append(('id','=',user_id.enterprise_id.id))

        return super(EtourismEnterprise, self).search(args, offset, limit, order, count=count)

class EtourismDirectoryEnterpriseRooms(models.Model):
    _name = 'etourism.directory.enterprise.room'
    _description = 'Directory Enterprise Rooms By Room Type'
    _rec_name = 'enterprise_id'

    enterprise_id = fields.Many2one('etourism.enterprise', string='Enterprise', required=True)
    room_type_id = fields.Many2one('product.category', string='Room type', domain=[('isroomtype', '=', True),('is_standard', '=', True)], required=True)
    num_rooms = fields.Integer("Number of rooms", required=True)
    num_beds = fields.Integer("Number of beds")
	
class EtourismEnterpriseAmenities(models.Model):
    _name = 'etourism.enterprise.amenity'
    _description = 'Enterprise Amenities'
    _rec_name = 'enterprise_id'

    enterprise_id = fields.Many2one('etourism.enterprise', string='Enterprise', required=True)
    amenity_id = fields.Many2one('etourism.amenities', string='Amenity', domain=[('amenity_type', '=', 'enterprise')], required=True)
    characteristics_line = fields.One2many('etourism.enterprise.amenity.characteristic', 'enterprise_amenity_id', string="Amenities Characteristics")
    featured = fields.Boolean("Featured",default=False)

    @api.model_cr
    def init(self):
        cr = self._cr
        tools.drop_view_if_exists(cr, 'view_amenity_enterprise')
        cr.execute("""
            CREATE OR REPLACE VIEW view_amenity_enterprise AS (
select ea.id,ea.enterprise_id,ea.amenity_id,
a.name as amenity_name,
e.name as name_enterprise,e.island_code,e.ebusiness_type_code,e.enterprise_type_id
from etourism_enterprise_amenity ea, etourism_enterprise e, etourism_amenities a
WHERE ea.amenity_id=a.id and ea.enterprise_id=e.id
            )"""
        );

class EtourismEnterpriseAmenitiesCharacteristics(models.Model):
    _name = 'etourism.enterprise.amenity.characteristic'
    _description = 'Enterprise Amenity Characteristics'

    enterprise_amenity_id = fields.Many2one('etourism.enterprise.amenity', string='Enterprise Amenity', required=True)
    name = fields.Char(string='Name', required=True)
    value = fields.Char(string='Value', required=True)

