# This file is part of Tradon. The COPYRIGHT file at the top level of
# this repository contains the full copyright notices and license terms.

from trytond.model import ModelSQL, ModelView, fields
from trytond.transaction import Transaction

__all__ = ['ConstraintType']


class ConstraintType(ModelSQL, ModelView):
    'Constraint Type'
    __name__ = 'trade_finance.constraint_type'
    _rec_name = 'name'

    name = fields.Char('Type', required=True, size=50)
    view_name = fields.Selection([], 'View')
    value_field = fields.Selection(
        'get_column_selection', 'Value Field',
        selection_change_with=['view_name'])
    label_field = fields.Selection(
        'get_column_selection', 'Label Field',
        selection_change_with=['view_name'])

    @fields.depends('view_name')
    def get_column_selection(self):
        if not self.view_name:
            return [('', '')]
        cursor = Transaction().connection.cursor()
        cursor.execute(
            "SELECT column_name FROM information_schema.columns "
            "WHERE table_schema = 'public' AND table_name = %s "
            "ORDER BY ordinal_position",
            (self.view_name,)
        )
        return [('', '')] + [(r[0], r[0]) for r in cursor.fetchall()]

    @fields.depends('view_name')
    def on_change_view_name(self):
        self.value_field = None
        self.label_field = None

    @classmethod
    def fields_get(cls, fields_names=None, level=0):
        res = super().fields_get(fields_names, level)
        if 'view_name' in res:
            cursor = Transaction().connection.cursor()
            cursor.execute(
                "SELECT table_name FROM information_schema.views "
                "WHERE table_schema = 'public' AND table_name LIKE 'vw_tf_const_%' "
                "ORDER BY table_name"
            )
            res['view_name']['selection'] = (
                [('', '')] + [(r[0], r[0]) for r in cursor.fetchall()])
        return res
