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

from odoo import fields, models, api
from odoo.exceptions import ValidationError
#import xlrd
import base64
import logging
from datetime import datetime, timedelta

_logger = logging.getLogger(__name__)

class kpi_snapshot_wizard(models.TransientModel):
    _name = "kpi.snapshot.wizard"
    _description = "Take Kpi SnapShot"

    @api.multi
    def action_snapshot_kpi_value(self):
        """Take Kpi SnapShot
        """
        kpis = self.env['kpi'].search([])
        print "RESULT : ", kpis

        for kpi in kpis:
            if kpi['values_query']:
                print "values_query: ",kpi['values_query']
                exceptions = ['delete', 'create']
                for x in exceptions:
                    if kpi['values_query'].lower().find(x) != -1:
                        raise ValidationError('You must insert a valid SQL query')
                try:
                    self._cr.execute(kpi['values_query'])
                    res = self._cr.fetchone()
                except Exception, e:
                    raise ValidationError(e)

                if len(res) < 2:
                    raise ValidationError('The query result must return 2 values, [0]="value" and [1]="max_value"')
                print "RES: ", len(res)

                value = int(res[0])
                max_value = int(res[1])
                kpi.last_snapshot = datetime.now()
                kpi_value = {
                    'kpi_id': kpi.id,
                    'date': kpi.last_snapshot,
                    'min_value': 0,
                    'max_value': max_value,
                    'value': value,
                    'polarity': '1'
                }


                kpi_value_id = self.env['kpi.value'].create(kpi_value).id

                if not kpi_value_id:
                    raise ValidationError("Not Possible to create This KPI Value")



