# -*- 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/>.
#
###############################################################################
import time

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 datetime import datetime

import odoo.addons.decimal_precision as dp

class EtourismProductPricelist(models.Model):
    _inherit = 'product.pricelist'
    _description = "Pricelists"

    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise')
    start_date = fields.Date(string='Start date',required=True)
    end_date = fields.Date(string='End date',required=True)
    publish_online = fields.Boolean(string='Publish Online?',default=True)
    has_default_enterprise = fields.Boolean('Has Default Enterprise', help="True, if User creating Booking group has related Enterprise.")
    pricelist_description = fields.Text(string='Pricelist Description')
    type_code = fields.Char(related="enterprise_id.type_id.code", string='Ebusiness Type',
                              store=True)
    #JCF 11-04-2018 - Reductions
    extra_bed_adults = fields.Float(string='Extra beds adults')
    extra_bed_first_child = fields.Float(string='Extra beds first child')
    extra_bed_second_child = fields.Float(string='Extra beds second child')
    extra_bed_infant = fields.Float(string='Extra beds infant')
    #JCF 30-01-2019
    online_pricelist = fields.Boolean(string='Online Pricelist',default=False)
    agencies_line = fields.One2many('etourism.pricelist.agency', 'pricelist_id',
                             string='Agencies')

    @api.model
    def default_get(self, fields):
        res = super(EtourismProductPricelist, self).default_get(fields)
        if self.env.uid:
            enterprise_id = self.env['res.users'].browse([self.env.uid])[0].enterprise_id
            if enterprise_id:
                res.update({'enterprise_id': enterprise_id.id, 'has_default_enterprise': True})
        return res

    @api.model
    def search(self, args, offset=0, limit=None, order=None, count=False):
        """ This function filters Pricelists on Etoursim Booking Lines based on Enterprise, Checkin & Checkout
        """
        #print "SEARCH PRICELISTS:::::::::::::::::::::::::::::::::::"
        context = self._context or {}

        if context and 'filter_enterprise_id' in context and 'filter_checkin' in context and 'filter_checkout' in context:
            pricelists = []
            #print "ENTROU NO IF:::::::::::::::::::::::::::::::::::"

            if context['filter_enterprise_id']:
                enterprise_id = context['filter_enterprise_id']
                checkin_date=context['filter_checkin']
                checkout_date=context['filter_checkout']
                self._cr.execute("""select id from product_pricelist where (start_date,end_date) overlaps ( '%s','%s' ) and enterprise_id=%s;"""%(checkin_date, checkout_date, enterprise_id)
                            )
                result = self._cr.fetchall()
                if result:
                    for res in result:
                        pricelists.append(res[0])
                    
            args += ([('id','in', pricelists)])
        return super(EtourismProductPricelist, self).search(args, offset, limit, order, count=count)

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):
        """ This function filters Pricelist Items on Etoursim Booking Lines based on Enterprise, Checkin & Checkout and room category
        """

        context = self._context or {}
        if context and 'filter_enterprise_id' in context and 'filter_checkin' in context and 'filter_checkout' in context:
            room_pricelists, pricelists = [], []
            if context['filter_enterprise_id']:
                enterprise_id = context['filter_enterprise_id']
                try:
                    date = datetime.strptime(context['filter_checkin'], "%Y-%m-%d %H:%M:%S").date()
                except :
                    date = datetime.strptime(context['filter_checkin'], "%Y-%m-%d").date()

                pricelists = self.env['product.pricelist'].search(
                    [('enterprise_id', '=', enterprise_id), ('start_date', '<=', date), ('end_date', '>=', date)])
                pricelist = []
                temp = [pricelist.append(x.id) for x in pricelists]
                result = []
                if pricelist:
                    result = self.search([('id', 'in', pricelist)])
                    res = []
                    temp = [res.append(x.id) for x in result]
                    if res:
                        args = [('id', 'in', res)]
                else:
                    args = [('id', 'in', [])]

        return super(EtourismProductPricelist, self).name_search(name, args, operator=operator, limit=limit)


class EtourismPricelistAgency(models.Model):
    _name = 'etourism.pricelist.agency'
    _rec_name = 'agency_id'

    pricelist_id = fields.Many2one('product.pricelist', 'Pricelist', index=True)
    agency_id = fields.Many2one('etourism.enterprise', 'Agency', required=True, index=True,domain=[('ebusiness_type_code', '=', 'AVT')])
    code = fields.Char('Code', index=True)
    discount = fields.Float('Discount', index=True)

class EtourismProductPricelistItems(models.Model):
    _inherit = 'product.pricelist.item'
    _description = "Pricelist items"

    booking_condition_id = fields.Many2one('etourism.booking.condition', 'Booking Condition')
    applied_on = fields.Selection([
        ('3_global', 'Global'),
        ('2_product_category', ' Product Category'),
        ('1_product', 'Product'),
        ('0_product_variant', 'Product Variant')], "Apply On",
        default='2_product_category', required=True,
        help='Pricelist Item applicable on selected option')
    enterprise_id = fields.Many2one('etourism.enterprise', related="pricelist_id.enterprise_id", string='Enterprise', store=True, readonly=True)
    max_adults = fields.Integer(string='Included Occupancy',required=True)
    max_occupancy = fields.Integer(string='Maximum Occupancy',required=True)
    max_children = fields.Integer(string='Number of children',required=True)
    additional_price = fields.Float('Additional Price', digits=dp.get_precision('Additional Price'))
    images = fields.One2many('etourism.pricelist.item.image', 'pricelist_item_id',
                             string='Images')

    @api.model
    def name_search(self, name, args=None, operator='ilike', limit=100):
        """ This function filters Pricelist Items on Etoursim Booking Lines based on Enterprise, Checkin & Checkout and room category
        """

        context = self._context or {}
        if context and 'filter_enterprise_id' in context and 'filter_checkin' in context and 'filter_checkout' in context and 'filter_room_id' in context and 'filter_pricelist_id' in context:
            room_pricelists, pricelists = [], []
            if context['filter_room_id'] and context['filter_pricelist_id']:
                room_id = context['filter_room_id']
                pricelist_id = context['filter_pricelist_id']
                print "ROOM ID: ",room_id
                print "PRICELIST ID: ",pricelist_id
                room = self.env['etourism.room'].search([('id','=',room_id)])
                if room:
                    room_categ = room[0].categ_id.id
                    print "ROOM CATEG ID: ",room_categ
                    r_pricelists = self.env['product.pricelist.item'].search([('categ_id','=',room_categ),('pricelist_id','=',pricelist_id)])
                    for pl in r_pricelists:
                        room_pricelists.append(pl.id)

                    if r_pricelists:
                        args = [('id','in', room_pricelists)]
                    else:
                        print "ELSE. NO PRICELIST:::::::::::::::: "
                        args = [('id', 'in', [])]
                else:
                    args = [('id', 'in', [])]
                    print "ELSE 2. NO PRICELIST:::::::::::::::: "

        elif context and 'filter_enterprise_id' in context and 'filter_date' in context and 'filter_package_id' in context:
            #print "ELIF PACKAGE::::::::::::::::::::::::: "
            package_pricelists, pricelists = [], []
            if context['filter_package_id']:
                package_id = context['filter_package_id']
                package = self.env['etourism.avt.package'].search([('id', '=', package_id)])
                if package:
                    p_pricelists = self.env['product.pricelist.item'].search([('package_id', '=', package.id)])
                    for pl in p_pricelists:
                        package_pricelists.append(pl.id)
            if context['filter_enterprise_id']:
                enterprise_id = context['filter_enterprise_id']
                try:
                    date = datetime.strptime(context['filter_date'], "%Y-%m-%d %H:%M:%S").date()
                except :
                    date = datetime.strptime(context['filter_date'], "%Y-%m-%d").date()

                pricelists = self.env['product.pricelist'].search(
                    [('enterprise_id', '=', enterprise_id), ('start_date', '<=', date), ('end_date', '>=', date)])
                pricelist = []
                temp = [pricelist.append(x.id) for x in pricelists]
                result = []
                if pricelist:
                    result = self.search([('pricelist_id', 'in', pricelist)])
                    res = []
                    temp = [res.append(x.id) for x in result]
                    res2 = []
                    for r in res:
                        if r in package_pricelists:
                            res2.append(r)
                    if res:
                        args = [('id', 'in', res2)]
                else:
                    args = [('id', 'in', [])]
        return super(EtourismProductPricelistItems, self).name_search(name, args, operator=operator, limit=limit)

    @api.multi
    def name_get(self):
        result = []
        for pritem in self:
            name = ' - '.join(filter(bool, [pritem.categ_id.name, pritem.booking_condition_id.name, str(pritem.fixed_price)]))
            result.append((pritem.id, name))
        return result

class EtourismPricelistItemImage(models.Model):
    _name = 'etourism.pricelist.item.image'
    _order = 'sequence, id DESC'

    name = fields.Char('Name')
    description = fields.Text('Description')
    sequence = fields.Integer('Sequence')
    image_alt = fields.Text('Image Label')
    image = fields.Binary('Image', required=True)
    image_small = fields.Binary('Small Image')
    pricelist_item_id = fields.Many2one('product.pricelist.item', 'Item', index=True)
    from_main_image = fields.Boolean('From Main Image', default=False)
