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

from openerp import _, api, models, fields

class SalesHelper(models.Model):

    _name = "lacagette.sales_helper"

    @api.model
    def get_product_template_data(self, id, params):
        """"""
        res = {'data': []}
        try:
            id = int(id) #  to prevent injection
            if params['interval'] == 'week':
                conf = self.env['ir.config_parameter']

                # Get stock movement location id
                if params['type'] == 'losses':
                    loc_id = conf.get_param("lacagette_sales_helper.losses_location_id")
                elif params['type'] == 'autoconso':
                    loc_id = conf.get_param("lacagette_sales_helper.autoconso_location_id")
                elif params['type'] == 'meals':
                    loc_id = conf.get_param("lacagette_sales_helper.meals_location_id")

                where_clause = """
                product_id = (SELECT id FROM product_product WHERE product_tmpl_id = """ + str(id) + """)
                AND state = 'done'
                AND location_dest_id = %s
                """ % loc_id

                sql = """
                SELECT to_char(date_trunc('week', create_date), 'YYYY-IW') as week , sum(product_uom_qty) as qty
                FROM stock_move WHERE %s
                GROUP BY week ORDER BY week asc
                """ % where_clause
                self.env.cr.execute(sql)
                p_stock_movement_data = self.env.cr.dictfetchall()

                sql_dates = """
                SELECT to_char(date_trunc('week', i::date), 'YYYY-IW') AS week
                FROM generate_series((SELECT MIN(create_date) FROM stock_move WHERE %s),
                                     now() + interval '1 week',
                                     '1 week'::interval) i
                """ % (where_clause)
                self.env.cr.execute(sql_dates)
                weeks = self.env.cr.dictfetchall()

                res['data'] = []
                res['labels'] = []
                nb_non_empty_weeks = non_empty_weeks_qty = 0
                for w in weeks:
                    res['labels'].append(w['week'])
                    qty = 0
                    for s in p_stock_movement_data:
                        if s['week'] == w['week']:
                            qty = s['qty']
                            nb_non_empty_weeks += 1
                            non_empty_weeks_qty += qty
                    res['data'].append(qty)
                res['nb_non_empty_weeks'] = nb_non_empty_weeks
                res['non_empty_weeks_qty'] = non_empty_weeks_qty
        except Exception as e:
            res['error'] = str(e)

        return res

class StockPicking(models.Model):
    _inherit = "stock.picking"

    # Add to picking table the id of the member who registered the picking
    operator_id = fields.Many2one('res.partner', string="Member who registered the picking")