from peewee import (
    IntegerField,
    CharField,
)
from peewee import SQL
from ..base import BaseModelSqlView, mysql_db


class WebviewPatientHisto(BaseModelSqlView):

    pk = IntegerField(
        column_name='x_pk', constraints=[SQL("DEFAULT 0")])
    nom_pat = CharField(
        column_name='x_nom_pat', null=True, constraints=[SQL("DEFAULT ''")])
    prenom_pat = CharField(
        column_name='x_prenom_pat', null=True, constraints=[SQL("DEFAULT ''")])

    def create_view(self):
        """Create the view in the database"""
        query ="""CREATE OR REPLACE VIEW webview_patient_histo AS
            SELECT DISTINCT `f_patient`.`x_pk` AS `x_pk`,  `f_patient`.`x_nom_pat` AS `x_nom_pat`, `f_patient`.`x_prenom_pat` AS `x_prenom_pat`
            FROM `f_patient`
            WHERE `f_patient`.`x_num_ipp` IN (SELECT DISTINCT `f_histo`.`x_num_ipp` FROM `f_histo`)"""  # noqa
        mysql_db.execute_sql(query)

    class Meta:
        table_name = 'webview_patient_histo'
