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

from openerp import api, fields, models, _
from openerp.exceptions import Warning
from openerp.addons.website_sale.controllers import main


class Brands(models.Model):
    _name = 'product.brands'

    name = fields.Char(string='Nombre de Marca', required=True, translate=True)
    brand_description = fields.Html(string='Descripción', translate=True)
    brand_logo = fields.Binary(string='Logo de Marca')
    brand_cover = fields.Binary(string='Logo Producto')
    product_ids = fields.One2many(
        'product.template',
        'product_brand_id',
        string='Marcas de Productos',
    )
    products_count = fields.Integer(
        string='Numero de Productos',
        compute='_get_products_count',
    )

    @api.one
    @api.depends('product_ids')
    def _get_products_count(self):
        self.products_count = len(self.product_ids)


class ProductStyleTags(models.Model):
    _name = 'biztech.product.style.tag'

    name = fields.Char(string='Nombre de Etiqueta', required=True, translate=True)
    color = fields.Selection(
        [('red', 'Rojo'), ('new', 'Verde'), ('sale', 'Naranja')], string="Color")
    product_ids = fields.One2many(
        'product.template',
        'product_style_tag_id',
        string='Etiqueta de Productos',
    )


class KingProductImages(models.Model):
    _name = 'biztech.product.images'
    _description = "Add Multiple Image in Product"

    name = fields.Char(string='Titulo', translate=True)
    alt = fields.Char(string='Alt', translate=True)
    attach_type = fields.Selection([('image', 'Image'), ('video', 'Video')],
                                   default='image',
                                   string="Tipo")
    image = fields.Binary(string='Imagen')
    video_type = fields.Selection([('youtube', 'Youtube'),
                                   ('vimeo', 'Vimeo'),
                                   ('html5video', 'Html5 Video')],
                                  default='youtube',
                                  string="Video media player")
    cover_image = fields.Binary(string='Imagen de Tapa',
                                # required=True,
                                help="Sera visto antes que el video cargue.")
    video_id = fields.Char(string='Video ID')
    video_ogv = fields.Char(string='Video OGV', help="Link for ogv format video")
    video_webm = fields.Char(string='Video WEBM', help="Link for webm format video")
    video_mp4 = fields.Char(string='Video MP4', help="Link for mp4 format video")
    sequence = fields.Integer(string='Orden de clasificación')
    product_tmpl_id = fields.Many2one('product.template', string='Producto')
    more_view_exclude = fields.Boolean(string="Excluir Ver más ")


class ProductTemplate(models.Model):
    _inherit = 'product.template'

    product_brand_id = fields.Many2one(
        'product.brands',
        string='Marca',
        help='Seleccionar Marca para éste Producto'
    )
    images = fields.One2many('biztech.product.images', 'product_tmpl_id',
                             string='Imagenes')
    multi_image = fields.Boolean(string="Agregar Imagenes Multiples?")
    tag_ids = fields.Many2many('biztech.product.tags', string="Etiquetas")
    is_flip_image = fields. Boolean(
        string="Agregar Imagen Cambiante", help="Habilita la opción de que se vea la imagen de atras, giro de imagen.")
    flip_image = fields.Binary(string='Flip imagen',
                               help="el giro de imagen se mostrará cuando el ratón pase por el producto específico.")
    product_style_tag_id = fields.Many2one(
        'biztech.product.style.tag',
        string='Etiquetas',
        help='Elija una Etiqueta para este producto'
    )


class ProductTags(models.Model):
    _name = 'biztech.product.tags'
    _order = "sequence"

    name = fields.Char(string="Nombre de Etiqueta", help="Tag Name", required=True, translate=True)
    active = fields.Boolean(
        string="Activo", help="Habilitar o desabilitar etiquetas en el sitio web", default=True)
    sequence = fields.Integer(
        string='Sequencia', help="You can define sequence of tags you want to show tags")
    product_ids = fields.Many2many('product.template', string='Productos', required=True)

    _sql_constraints = [('unique_tag_name', 'unique(name)', 'Etiqueta debe ser unico..!'), ]


class ProductSortBy(models.Model):
    _name = 'biztech.product.sortby'

    name = fields.Char(string="Nombre", help='Name for sorting option', translate=True,
                       required=True)
    sort_type = fields.Selection(
        [('asc', 'Ascendiente'), ('desc', 'Descendiente')], string="Tipo", default='asc')
    sort_on = fields.Many2one('ir.model.fields', string='Ordenar por',
                              help='Select field on which you want to apply sorting',
                              domain=[('model', '=', 'product.template'), ('ttype', 'in', ('char', 'float', 'integer', 'datetime', 'date'))])


class ProductCategory(models.Model):
    _inherit = 'product.public.category'

    include_in_megamenu = fields.Boolean(
        string="Incluir en el Mega Menu", help="Incluye en el menu")
    menu_id = fields.Many2one('website.menu', string="Menu Principal")
    description = fields.Text(string="Descripción",
                              help="Breve descripción que será visible por debajo de la categoría.")


class ProductPerPageNo(models.Model):
    _name = "product.per.page.no"
    _order = 'name asc'

    name = fields.Integer(string='Productos por Página')
    set_default_check = fields.Boolean(string="Colocar como Predeterminado")
    prod_page_id = fields.Many2one('product.per.page')

    @api.model
    def create(self, vals):
        res = super(ProductPerPageNo, self).create(vals)
        if vals.get('name') == 0:
            raise Warning(_("Warning! You cannot set 'zero' for product page."))
        if vals.get('set_default_check'):
            true_records = self.search(
                [('set_default_check', '=', True), ('id', '!=', res.id)])
            true_records.write({'set_default_check': False})
        return res

    @api.multi
    def write(self, vals):
        res = super(ProductPerPageNo, self).write(vals)
        if vals.get('name') == 0:
            raise Warning(_("Warning! You cannot set 'zero' for product page."))
        if vals.get('set_default_check'):
            true_records = self.search(
                [('set_default_check', '=', True), ('id', '!=', self.id)])
            true_records.write({'set_default_check': False})
        return res


class ProductPerPage(models.Model):
    _name = "product.per.page"

    name = fields.Char(string="Nombre de Etiqueta", translate=True)
    no_ids = fields.One2many(
        'product.per.page.no', 'prod_page_id', string="Nº de productos a mostrar")

    @api.multi
    def write(self, vals):
        res = super(ProductPerPage, self).write(vals)
        default_pg = self.env['product.per.page.no'].search([('set_default_check', '=', True)])
        if default_pg.name:
            main.PPG = int(default_pg.name)
        else:
            raise Warning(_("Warning! You have to set atleast one default value."))
        return res