from ..base import BaseView
# from peewee import DoesNotExist, IntegrityError
# from median.database import mysql_db
import logging

logger = logging.getLogger('median')


class Dispensation(BaseView):

    def affichage(self, service, ipp='', v_orderby_column='', v_dir='', fusion=''):
        """View class to represent a dispensation"""
        """
        Display the list of the dispensation

        :param service: code of the ward
        :type service: str
        :param ipp: Patient identification
        :type  ipp: str
        :param v_orderby_column: name of the column to order the result
        :type  v_orderby_column: str
        :param v_dir: limit result
        :type  v_dir: str
        """
        query = """
              SELECT l.x_pk, l.x_code_liv, l.x_liste, concat(x_nom_pat,' ',x_prenom_pat) as x_nom
                FROM  f_liste l
                inner join f_patient p ON l.x_num_ipp=p.x_num_ipp
               WHERE l.x_mode='S' and x_dest='{0}' and x_fusion='{1}' and l.x_num_ipp like '%%{2}%%' order by {3} {4}
        """.format(service, fusion, ipp, v_orderby_column, v_dir)
        return self.render_query(query)


class Items(BaseView):

    def affichage(self, service, v_orderby_column, v_dir):
        """
        Display the items of the dispensation

        :param service: code of the ward
        :type service: str
        :param ipp: Patient identification
        :type  ipp: str
        :param v_orderby_column: name of the column to order the result
        :type  v_orderby_column: str
        :param v_dir: limit result
        :type  v_dir: str
        """
        query = """
              SELECT i.x_pk, i.x_item, i.x_etat, i.x_ref, i.x_fraction,
                     x_desig, x_qte_dem, x_qte_serv, x_moment, x_heure
                FROM  f_item i
                inner join f_ref r ON i.x_ref=r.x_ref
               WHERE x_mode='S' and x_liste='{0}' order by {1} {2}
        """.format(service, v_orderby_column, v_dir)
        return self.render_query(query)


class Dispensation_Suggestion(BaseView):

    def affichage(self, filtre, v_orderby_column, v_dir):
        """
        Display the suggestion of the dispensation

        :param filtre: Patient number
        :type filtre: str
        :param v_orderby_column: name of the column to order the result
        :type  v_orderby_column: str
        :param v_dir: limit result
        :type  v_dir: str
        """
        query = """
              SELECT distinct l.x_num_ipp, concat(x_nom_pat,' ',x_prenom_pat) as x_nom
                FROM  f_liste l
                inner join f_patient p ON l.x_num_ipp=p.x_num_ipp
               WHERE l.x_mode='S' and l.x_num_ipp like '%%{0}%%' order by l.{1} {2}
        """.format(filtre, v_orderby_column, v_dir)
        return self.render_query(query)
