# -*- coding: utf-8 -*-
# Copyright 2016 Onestein (<http://www.onestein.eu>)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from lxml import etree

from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools.safe_eval import safe_eval
from odoo.tools.translate import _

class kpi_type(models.Model):
    _name = 'kpi.type'
    _description = 'KPI Type'

    name = fields.Char('Name', required=True)
    code = fields.Char('Code')

class Kpi(models.Model):
    _name = 'kpi'
    _description = 'Key Performance Indicators - KPI'

    name = fields.Char('Name', required=True)
    acronym = fields.Char('Denomination / Acronym')
    definition = fields.Char('Definition')
    description = fields.Text('Description')
    goal = fields.Float('Goal')
    calcule = fields.Char('Calcule')
    view = fields.Html('View')
    periodicity = fields.Selection([('monthly', 'Monthly'),
                              ('quarterly', 'Quarterly'),('semester', 'Semester'),('annualy', 'Annualy')], 'Periodicity', default='monthly')
    polarity = fields.Selection([('-', '(-)'),
                              ('+', '(+)')], 'Polarity')
    #polarity = fields.Float('Polarity')
    source = fields.Char('Source')
    reason = fields.Char('Reason')
    dimension_variables = fields.Char('Dimension Variables')
    statistical_analysis = fields.Char('Statistical analysis')
    publication_periodicity = fields.Selection([('monthly', 'Monthly'),
                              ('quarterly', 'Quarterly'),('semester', 'Semester'),('annualy', 'Annualy')], 'Periodicity of publication', default='monthly')
    degree_confidentiality = fields.Char('Degree of confidentiality')
    complementary_indicators = fields.Char('Complementary indicators')
    additional_notes = fields.Text('Additional Notes')
    kpi_type_id = fields.Many2one('kpi.type', 'KPI Type')
    input_ids = fields.Many2many('kpi.input', 'kpi_input_kpi_rel',
                                'input_id', 'kpi_id', string='Inputs')
    values_query = fields.Text(string='Query')
    last_snapshot=fields.Datetime('Last SnapShot',readonly=True)

    @api.model
    def create(self, vals):
        print "CREATE KPI: ", vals
        """
        Overrides orm create method.
        @param self: The object pointer
        @param vals: dictionary of fields value.
        """
        value = 0
        kpi_id = None
        if not vals:
            vals = {}
        if self._context is None:
            self._context = {}

        result = self.env['kpi'].search([('name', '=', vals['name'])])
        print "RESULT : ", result

        if (result):
            raise ValidationError('This Kpi Already Exist')

        if 'values_query' in vals:
            exceptions = ['delete', 'create']
            for x in exceptions:
                if vals['values_query'].lower().find(x) != -1:
                    raise ValidationError('You must insert a valid SQL query')
            try:
                self._cr.execute(vals['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)
        return super(Kpi, self).create(vals)


class kpi_value(models.Model):
    _name = 'kpi.value'
    _rec_name = 'kpi_id'
    _description = 'KPI Gauge'

    kpi_id = fields.Many2one('kpi', 'KPI', required=True)
    date = fields.Datetime('Date')
    min_value = fields.Float('Min Value')
    max_value = fields.Float('Max Value')
    value = fields.Float('Value')
    polarity=fields.Selection([('-1', '(-)'), ('1', '(+)')], 'Polarity')

	
class kpi_domain(models.Model):
    _name = 'kpi.domain'
    _description = 'Domain'

    name = fields.Char(string="Name", required=True)
    domain = fields.Char(string="Domain", required=True)
    value = fields.Char(string="Value", required=True)


