# This file is part of Tryton.  The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.
from datetime import datetime, date
from trytond.report import Report
from trytond.model import ModelView, ModelSQL, fields, Workflow
from trytond.pyson import Eval, If, In, Get
from trytond.pool import Pool, PoolMeta
from trytond.transaction import Transaction
from .exceptions import CrmConfigurationError
from trytond.i18n import gettext
from trytond.modules.company.model import employee_field, set_employee


class ValidationTemplate(ModelSQL, ModelView):
    "Validation Template"
    __name__ = "crm.validation_template"
    name = fields.Char('Name', required=True, select=True)
    code = fields.Char('Code', required=True, select=True)
    type = fields.Selection([
        ('prospect', 'Prospect'),
        ('client', 'Client')
        ], 'Type')
    active = fields.Boolean('Active')
    lines = fields.One2Many('crm.validation_template.ask',
        'template', 'Asks')


class ValidationTemplateAsk(ModelSQL, ModelView):
    "Validation Template Ask"
    # Ask/concept for each template
    __name__ = "crm.validation_template.ask"
    _rec_name = 'ask'
    template = fields.Many2One('crm.validation_template',
        'Template Validation', required=True)
    sequence = fields.Integer('Sequence', required=True, select=True)
    ask = fields.Char('Ask', required=True, select=True)


class OpportunityValidation(ModelSQL, ModelView):
    "Opportunity Validation"
    # Validation for each opportunity
    __name__ = "crm.opportunity.validation"
    _history = True
    opportunity = fields.Many2One('crm.opportunity', 'Opportunity',
        required=True)
    party = fields.Many2One('party.party', 'Party', required=True)
    template = fields.Many2One('crm.validation_template.ask',
        'Template Ask', required=True)
    sequence = fields.Integer('Sequence', required=True)
    date_validation = fields.Date('Date')
    line_ask = fields.Char('Ask', required=True, select=True)
    # response = fields.Boolean('Response')
    response = fields.Selection([
        ("", ""),
        ('approved', 'Approved'),
        ('rejected', 'Rejected'),
    ], "Response")
    comment = fields.Text('Comments')
    validated_by = fields.Many2One('res.user', 'User')
    blocked = fields.Boolean('Blocked', readonly=True)
    history = fields.Function(fields.Text('history'), 'get_history')

    @classmethod
    def __setup__(cls):
        super(OpportunityValidation, cls).__setup__()
        cls._order.insert(0, ('sequence', 'ASC'))

    def get_user(self, name):
        return self.create_uid.rec_name

    def get_history(self, name):
        # return 'Historial'
        list_ids = [self.id,]
        show_list_as_str = 'Fecha | Pregunta | Usuario' + '\n'
        OpportunityHistory = Pool().get('crm.opportunity.validation')
        HistoryByAsk = OpportunityHistory.history_revisions(list_ids)
        for record in HistoryByAsk:
            show_list_as_str += str(record[0]) + ' | ' + str(record[1]) + ' | ' + str(record[2]) + '\n'
        return str(show_list_as_str)

    @fields.depends('response')
    def on_change_response(self):
        if self.response:
            self.validated_by = Transaction().user
            self.date_validation = date.today()
        else:
            self.date_validation = None


class ValidationHistoryAsk(ModelView, ModelSQL):
    "Validation History Ask"
    __name__ = "crm.opportunity.validation.history"
    id = fields.Integer('id')
    company = fields.Many2One('company.company', 'Company')
    line_ask = fields.Char('Ask')
    response = fields.Char('Response')
    opportunity = fields.Integer('Opportunity')
    comment = fields.Text('Comments')
    validated_by = fields.Integer('Validated By')

    @classmethod
    def table_query(cls):
        OpportunityHistory = Pool().get('crm.opportunity.validation')
        Opportunity = Pool().get('crm.opportunity')
        opportunityhistory = OpportunityHistory.__table_history__()
        opportunity = Opportunity.__table__()
        query = opportunityhistory.join(opportunity,
            condition=opportunity.id==opportunityhistory.opportunity
            ).select(
            opportunityhistory.id,
            opportunityhistory.create_uid,
            opportunityhistory.create_date,
            opportunityhistory.write_uid,
            opportunityhistory.write_date,
            # Literal(0).as_('create_uid'),
            # CurrentTimestamp().as_('create_date'),
            # cls.write_uid.sql_cast(Literal(Null)).as_('write_uid'),
            # cls.write_date.sql_cast(Literal(Null)).as_('write_date'),
            opportunity.company,
            opportunityhistory.line_ask,
            opportunityhistory.comment,
            # opportunity.date_validation,
            opportunityhistory.opportunity,
            opportunityhistory.validated_by,
            # opportunity.party,
            # opportunity.response,
            # opportunity.sequence,
            # opportunity.template,
            opportunityhistory.response,

            )
        cursor = Transaction().connection.cursor()
        cursor.execute(*query)
        result = cursor.fetchall()
        return query


# class PartyValidationTraceability(ModelSQL, ModelView):
#     ''' Model to save traceability of the Party Validation'''
#     'Party Validation Traceability'
#     __name__ = 'crm.party_validation_traceability'
#     response = fields.Selection([
#         ("", ""),
#         ('approved', 'Approved'),
#         ('rejected', 'Rejected'),
#     ], "Response")
#     opportunity = fields.Many2One('crm.opportunity', 'Opportunity', required=True )
#     comment = fields.Text('Comments')
#     validated_by = fields.Many2One('res.user', 'User')
