# -*- 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,tools, _
import urlparse

class ProductTemplate(models.Model):

    _inherit = "product.template"

    is_package = fields.Boolean('Is Package',default=False)

class ProductProduct(models.Model):

    _inherit = "product.product"

    ispackage = fields.Boolean('Is Package',default=False)


class EtourismAVTPackageType(models.Model):
    _inherit = 'product.category'
    _description = "Package Types"

    code = fields.Char('Code', index=True, required=True)
    ispackage = fields.Boolean('Is Package')

class EtourismAVTPackageImage(models.Model):
    _name = 'etourism.avt.package.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')
    image_small = fields.Binary('Small Image')
    package_id = fields.Many2one('etourism.avt.package', 'Package', select=True)
    from_main_image = fields.Boolean('From Main Image', default=False)
    url = fields.Text('Image Url')

    @api.model
    def create(self, vals):
        print "########################### CREATE PACKAGE IMAGE ###########################"
        if not vals:
            vals = {}
        if self._context is None:
            self._context = {}
        image = super(EtourismAVTPackageImage, self).create(vals)
        image.url = self.sudo().get_image_url('etourism.avt.package.image', 'image', image.id)
        print "PACKAGE IMAGE: ", image.url

    @api.multi
    def get_image_url(self, model, field, rec_id):
        url = ''
        if model and rec_id:
            base_url = self.env['ir.config_parameter'].get_param('web.base.url')
            url = "%s" % urlparse.urljoin(base_url, 'web/image/%s/%s/%s' % (model, rec_id, field))
        return url


class EtourismAVTPackage(models.Model):
    _name = 'etourism.avt.package'
    _inherits = {'product.product': 'product_id'}
    _inherit = ['ir.needaction_mixin', 'mail.thread']
    _description = "Packages"

    enterprise_id = fields.Many2one('etourism.enterprise', 'Enterprise',required=True,domain=[('ebusiness_type_code', '=', 'AVT')])
    product_id = fields.Many2one(
        'product.product', 'Product', required=True, ondelete="cascade", track_visibility='onchange')
    description = fields.Text('Description',required=True)
    locations = fields.Many2many('ecom.location', 'package_location_rel', 'package_id', 'location_id',
                                 string='Location(s)', required=True, domain=[('level', '=', 3)])
    schedule = fields.Html('Itinerary',required=True)
    has_default_enterprise = fields.Boolean('Has Default Enterprise', help="True, if User creating Booking group has related Enterprise.")
    images = fields.One2many('etourism.avt.package.image', 'package_id',string='Images')
    images_url=fields.Text('Images Url',store=True)
    image_url=fields.Text('Image Url',store=True, compute='set_image_url')
    video_url=fields.Text('Video Url')
    duration = fields.Integer(string='Duration', default='1',required=True)
    status = fields.Selection([('Available', 'Available'),
                               ('Unvailable', 'Unavailable'),
                               ], 'Status', default='Available', track_visibility='onchange')
    duration_measure = fields.Selection([('hour', 'Hour'),('day', 'Day'),('week', 'Week'),('month', 'Month')], 'Measure', default='day',required=True, track_visibility='onchange')
    #package_type_id = fields.Many2one(related="product_id.product_tmpl_id.categ_id", string='Package Type', store=True)
    package_type_id = fields.Many2one('product.category', 'Package Type',required=True,domain=[('ispackage', '=', True)])
    code = fields.Char('Code', index=True, required=True)
    book_before = fields.Integer(string='Book Before (days)',default=0)
    terms_and_conditions = fields.Html('Terms and Conditions',required=True)
    terms_and_conditions_en = fields.Html('Terms and Conditions EN')
    description_en = fields.Text('Description EN')
    schedule_en = fields.Html('Itinerary EN')

    @api.multi
    def copy(self, default=None):
        '''
        @param self: object pointer
        @param default: dict of default values to be set
        '''
        name = _("%s (copy)") % self.name
        print "name: ",name
        default = dict(default or {}, name=name)
        print "default: ",default

        return super(EtourismAVTPackage, self).copy(default=default)

    @api.multi
    def get_image_url(self, model, field, rec_id):
        url = ''
        if model and rec_id:
            base_url = self.env['ir.config_parameter'].get_param('web.base.url')
            url = "%s" % urlparse.urljoin(base_url, 'web/image/%s/%s/%s' % (model, rec_id, field))
        return url

    @api.multi
    @api.onchange('image_medium')
    def set_image_url(self):
        print "IMAGE CHANGE"
        self.image_url = self.sudo().get_image_url('etourism.avt.package', 'image', self.id)

    @api.model
    def default_get(self, fields):
        res = super(EtourismAVTPackage, 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, 'ispackage': True, 'is_package': True,'available_in_pos':False})
            else:
                res.update({'ispackage': True, 'is_package': True,'isroom_available':True,'available_in_pos':False})
        return res

    @api.model
    def create(self, vals):
        print "########################### CREATE PACKAGES ###########################"
        if not vals:
            vals = {}
        if self._context is None:
            self._context = {}

        vals['website_published']=True
        package=super(EtourismAVTPackage, self).create(vals)
        package.image_url = self.sudo().get_image_url('etourism.avt.package', 'image', package.id)
        print "PACKAGE IMAGE: ", package.image_url


        if package.product_id and package.enterprise_id:
            var_product_id = package.product_id.id
            var_enterprise_id = package.enterprise_id.id

            package_product = self.env['product.product'].search([('id', '=', var_product_id)], limit=1)
            if package_product:
                product_tmpl_id=package_product.product_tmpl_id.id
                self._cr.execute("""UPDATE product_template SET enterprise_id=%s WHERE id=%s"""%(var_enterprise_id,product_tmpl_id))
        return package

    @api.multi
    def write(self, vals):
        print "########################### WRITE PACKAGES ###########################"
        """
        Overrides orm write method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        update Hotel Room history"""
        count=0
        var_product_id=False
        var_enterprise_id=False

        for room in self:

            if 'enterprise_id' in vals:
                var_enterprise_id = vals['enterprise_id']
            else:
                var_enterprise_id = self.enterprise_id.id

            if 'product_id' in vals:
                var_product_id = vals['product_id']
            else:
                var_product_id = self.product_id.id

            if var_product_id:
                package_product = self.env['product.product'].search([('product_tmpl_id', '=', var_product_id)], limit=1)
                if package_product:
                    product_tmpl_id=package_product.product_tmpl_id.id
                    self._cr.execute("""UPDATE product_template SET enterprise_id=%s WHERE id=%s"""%(var_enterprise_id,product_tmpl_id))
            image_url = self.sudo().get_image_url('etourism.avt.package', 'image', self.id)
            print "PACKAGE IMAGE: ", image_url
            self._cr.execute("""UPDATE etourism_avt_package SET image_url='%s' WHERE id=%s""" % (image_url, self.id))

        return super(EtourismAVTPackage, self).write(vals)

    @api.model_cr
    def init(self):
        cr = self._cr
        tools.drop_view_if_exists(cr, 'package_view')
        cr.execute("""
               CREATE OR REPLACE VIEW package_view AS
           SELECT pl1.id AS item_id,
           ep.id AS package_id,
           pl1.fixed_price AS price,
           t.name,
           ep.code,
           pc.name as type,
           pc.code as type_code,
           ep.schedule AS schedule,
           ep.description AS description,
           ep.book_before,
           pl1.min_quantity,
           pl1.max_occupancy,
           ep.enterprise_id,
           ee.name as enterprise_name,
           eb.sequence_code as enterprise_code,
           pl.start_date,
           pl.end_date,
          '['||ep.duration||',"'||ep.duration_measure||'"]' as duration,
           (
            select string_agg(epi.url, ',')
            from etourism_avt_package_image epi
            where epi.package_id=ep.id
          )	as images_url,
          case 
            when ep.image_url IS NULL then 'false'
               else ep.image_url
            end as image_url,
          case 
            when ep.video_url IS NULL then 'false'
               else ep.video_url
            end as video_url,
           ep.terms_and_conditions AS terms_and_conditions,
           ep.terms_and_conditions_en AS terms_and_conditions_en,
           ep.schedule_en AS schedule_en,
           ep.description_en AS description_en,
		   pl1.fixed_price_euros as price_euros
          FROM product_pricelist pl,
           product_category pc,
           product_pricelist_item pl1,
           etourism_avt_package ep,
           product_product p,
           product_template t,
           etourism_enterprise ee,
           ecom_ebusiness eb
         WHERE pl.id = pl1.pricelist_id AND
          pl1.enterprise_id = pl.enterprise_id AND
          ep.enterprise_id = pl.enterprise_id AND
          ep.enterprise_id = ee.id AND
          ee.ebusiness_id=eb.id AND
          ep.id = pl1.package_id AND
          ep.product_id = p.id AND
          ep.package_type_id = pc.id AND
          p.product_tmpl_id = t.id AND
          pl.start_date <= now() AND
          pl.end_date >= now() 
         ORDER BY ep.id,pl1.max_occupancy;""")

        cr.execute("""
            CREATE OR REPLACE VIEW package_location_view as (SELECT plr.package_id,el.code,el2.code as parent_code_level2,el3.code as parent_code_level3
            FROM package_location_rel plr ,ecom_location el,ecom_location el2,ecom_location el3
            where el.id=plr.location_id AND el2.id=el.parent_id AND el3.id=el2.parent_id)
        """)

        cr.execute("""
            CREATE OR REPLACE FUNCTION get_match_location(integer, varchar)
              RETURNS integer AS
            $BODY$ declare
                v_return integer:=0;
             begin
            
                select count(*) into v_return from package_location_view WHERE (code=$2 OR parent_code_level2=$2 OR parent_code_level3=$2) and package_id=$1;
            
                return v_return;
             end;$BODY$
              LANGUAGE plpgsql VOLATILE
        """)


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


