# -*- coding: utf-8 -*-
# Part of BiztechCS. See LICENSE file for full copyright and licensing details.

from datetime import date
import openerp
from openerp import api, fields, models, _
from openerp.http import request
from openerp.addons.website.models.website import slugify


class product_template(models.Model):
    _inherit = "product.template"

    is_arrival = fields.Boolean(string='Arrival Products', default=False)
    is_features = fields.Boolean(string='Feature Products', default=False)


class res_partner(models.Model):
    _description = 'Supplier Brand'
    _inherit = "res.partner"

    is_home_brand = fields.Boolean(string='Brand', default=False)


class website(models.Model):
    _inherit = 'website'

    def get_arrival_product(self):
        template_obj = self.env['product.template']
        prod_ids = template_obj.search(
            [('is_arrival', '=', 'True'), ("sale_ok", "=", True)])
        if prod_ids and len(prod_ids) > 16:
            prod_ids = prod_ids[:16]
        elif prod_ids and len(prod_ids) <= 16:
            prod_ids = prod_ids
        price_list = self.price_list_get()
        return prod_ids

    def price_list_get(self):
        user = request.env.user
        if user:
            price_list = user.partner_id.property_product_pricelist
            return price_list.id
        return True

    def get_feature_product(self):
        template_obj = self.env['product.template']
        prod_ids = template_obj.search([('is_features', '=', 'True'),
                                        ("sale_ok", "=", True)])
        if prod_ids and len(prod_ids) > 8:
            prod_ids = prod_ids[:8]
        elif prod_ids and len(prod_ids) <= 8:
            prod_ids = prod_ids
        price_list = self.price_list_get()
        return prod_ids

    def get_brand_img(self):
        partner_obj = self.env['res.partner']
        brands = partner_obj.search([('is_home_brand', '=', 'True')])
        return brands

    def get_current_year(self):
        return date.today().year

    def new_page(self, cr, uid, name, template='website.default_page', ispage=True, context=None):
        context = context or {}
        imd = self.pool.get('ir.model.data')
        view = self.pool.get('ir.ui.view')
        template_module, template_name = template.split('.')

        # completely arbitrary max_length
        page_name = slugify(name, max_length=50)
        page_xmlid = "%s.%s" % (template_module, page_name)

        # find a free xmlid
        inc = 0
        dom = [('website_id', '=', False), ('website_id', '=', context.get('website_id'))]
        while view.search(cr, openerp.SUPERUSER_ID, [('key', '=', page_xmlid), '|'] + dom, context=dict(context or {}, active_test=False)):
            inc += 1
            page_xmlid = "%s.%s" % (template_module, page_name + (inc and "-%s" % inc or ""))
        page_name += (inc and "-%s" % inc or "")

        try:
            # existing page
            imd.get_object_reference(cr, uid, template_module, page_name)
        except ValueError:
            # new page
            _, template_id = imd.get_object_reference(cr, uid, template_module, template_name)
            website_id = context.get('website_id')
            key = template_module+'.'+page_name
            page_id = view.copy(cr, uid, template_id, {'website_id': website_id, 'key': key}, context=context)
            page = view.browse(cr, uid, page_id, context=dict(context, lang=None))
            page.write({
                'arch': page.arch.replace(template, page_xmlid),
                'name': page_name,
                'page': ispage,
            })
            page1 = view.browse(cr, uid, page_id, context=context)
            arch = '<?xml version="1.0"?><t t-name="website.'+str(page_name)+'"><t t-call="website.layout"> \
                    <div id="wrap" class="oe_structure oe_empty"><div class="page-title"><div class="container">\
                    <h1>'+str(page_name.capitalize())+'</h1> \
                    <ul class="breadcrumb"><li><a href="/page/homepage">Home</a>\
                    </li><li class="active">'+str(page_name.capitalize())+'</li></ul></div></div></div></t></t>'
            page1.write({'arch': arch})
            imd.create(cr, uid, {
                'name': page_name,
                'module': template_module,
                'model': 'ir.ui.view',
                'res_id': page_id,
                'noupdate': True
            }, context=context)
        return page_xmlid

    def get_default_newsletter(self):
        data = self.env['mail.mass_mailing.list'].search([], order='id')
        if data:
            return data[0]
        return False
