#By default id is not showed

from paramecio2.libraries.pages import Pages
from paramecio2.libraries.urls import add_get_parameters
from paramecio2.libraries.i18n import I18n
from flask import request, session
import sys
import re

class SimpleList:
    
    def __init__(self, model, url, t):
        
        self.raw_query=True
        
        self.t=t
        
        self.model=model
        
        #if len(self.model.forms)==0:
        
            #self.model.create_forms()
        
        self.fields=model.fields.keys()
        
        self.fields_showed=self.fields
        
        self.url=url
        
        self.limit_pages=20
        
        self.order_defaults=['ASC', 'DESC']
        
        self.order_class=['down', 'up']
        
        #self.s=get_session()
        
        #clean session
        
        self.order='0'
        
        self.order_field=self.model.name_field_id
        
        self.order_by=self.order_defaults[0]
        
        self.change_order={}
        
        self.yes_search=True
        
        self.search_text=''
        
        self.initial_num_pages=20
        
        self.table_div=False
        
        try: 
        
            self.begin_page=int(request.args.get('begin_page', '0'))
            
        except ValueError:
            self.begin_page=0
        
        if self.begin_page<0:
            self.begin_page=0
        
        self.search_fields=self.fields
        
        #self.yes_options=True
        
        self.arr_extra_fields=[I18n.lang('common', 'options', 'Options')]
        
        self.arr_extra_options=[SimpleList.standard_options]
        
        self.jln='<br />'

        self.ajax=False

    def restore_fields(self):
        self.fields=self.model.fields.keys()
    
    def obtain_order(self):
        
        self.order=request.args.get('order', self.order) #self.getpostfiles.get.get('order', self.order)
        
        order_k=int(self.order)
        
        #Obtain from get
        """
        if 'order' in request.query.keys():
        """
        #order_k=int(request.query.get('order', 0))
        
        if order_k>1 or order_k<0:
            order_k=0
        
        self.order_by=self.order_defaults[ order_k ]
        
        self.order=order_k
    
    def obtain_field_search(self):
        
        self.order_field=request.args.get('order_field', self.order_field)
        
        field_k=self.order_field
        
        """
        if 'order_field' in request.query.keys():
            field_k=request.query.order_field
        """
        
        if field_k in self.model.fields.keys():
            
            self.order_field=field_k
        
        for field in self.fields:
            
            #Initialize foreignkeyfield fields too
            
            if type(self.model.fields[field]).__name__=='ForeignKeyField':
                name_related=self.model.fields[field].related_model.name
                for k in self.model.fields[field].related_model.fields.keys():
                    self.change_order[field+'_'+k]=self.order
            
            self.change_order[field]=self.order
        
        if self.order==0:
            self.change_order[field_k]=1
        else:
            self.change_order[field_k]=0
        
        #self.order_field=self.order_field
        
    def search(self):
        
        self.search_text=request.args.get('search_text', '')
        
        self.search_text=self.search_text.replace('"', '&quot;')
        
        #self.model.conditions='AND 
        
        self.search_field=request.args.get('search_field', '')
        
        if self.search_field not in self.model.fields.keys():
            self.search_field=''
        
        if self.search_field!='' and self.search_text!='':
            self.model.conditions[0]+=' AND '+self.search_field+' LIKE %s'
            self.model.conditions[1].append('%'+self.search_text+'%')
        
        pass
    
    def set_options(self, options_func, arr_row):
        #SimpleList.standard_options(arr_row)
        return self.jln.join(options_func(self.url, arr_row[self.model.name_field_id], arr_row)) 
    
    @staticmethod
    def standard_options(url, id, arr_row):
        options=[]
        options.append('<a href="'+add_get_parameters(url, op_admin=1, id=id)+'">'+I18n.lang('common', 'edit', 'Edit')+'</a>')
        options.append('<a href="'+add_get_parameters(url, op_admin=3, id=id)+'">'+I18n.lang('common', 'delete', 'Delete')+'</a>')
        return options
    
    def show(self):
        
        self.model.yes_reset_conditions=False
        
        self.obtain_order()
        
        self.obtain_field_search()
        
        self.search()
        
        total_elements=self.model.select_count()
        
        num_elements=self.limit_pages
        
        link=add_get_parameters(self.url, search_text=self.search_text, search_field=self.search_field, order=self.order)
        
        begin_page=self.begin_page
        
        self.model.order_by='order by '+self.order_field+' '+self.order_by

        if self.limit_pages>0:
        
            self.model.limit='limit '+str(begin_page)+','+str(self.limit_pages)
        
        list_items=self.model.select(self.fields, self.raw_query)
        
        #print(self.model.fields.keys())
        
        func_jscript=''
        
        if self.ajax==True:
            func_jscript='get_page()'
            
        pages=''

        if self.limit_pages>0:        
            pages=Pages.show( begin_page, total_elements, num_elements, link ,initial_num_pages=self.initial_num_pages, variable='begin_page', label='', func_jscript='')
        
        self.begin_page=str(self.begin_page)
        
        self.model.yes_reset_conditions=True
        
        listing=self.t.load_template('utils/list.phtml', simplelist=self, list=list_items, pages=pages, ajax=self.ajax)
        
        list_items.close()
        
        return listing

    @staticmethod
    def get_ajax_page(model):
        
        
        
        pass
        
    
class AjaxList(SimpleList):
    
    # Fields example: [[I18n.lang('cuchulu', 'hostname', 'Hostname'), True], ['IP', True], [I18n.lang('cuchulu', 'options', 'Options'), False]]
    
    # arr_order_fields=['server.hostname', 'server.ip']
    
    # 'select count(servercloud.id) as num_elements from servercloud where servercloud.user_id=%s'
    # params count_query [s['cu_id']]
    
    # str_query no order, no limit -> select server.hostname, server.ip, servercloud.id from server, servercloud where server.id=servercloud.server_id and servercloud.user_id=%s
    # str_query_params -> [s['cu_id'], begin_page, limit]
    
    def __init__(self, db, fields, arr_order_fields, count_query, str_query):
        
        self.fields=fields
        self.arr_order_fields=arr_order_fields
        self.limit=20
        self.count_query=count_query[0]
        self.count_query_params=count_query[1]
        self.str_query=str_query[0]
        self.str_query_params=str_query[1]
        self.initial_num_pages=20
        self.db=db
        self.func_fields={}
        
    def show(self):
        
        begin_page=int(request.args.get('position', 0))
        order_field=request.args.get('order_field', '')
        order=request.args.get('order', 0)
        limit=self.limit

        arr_order=['ASC', 'DESC']
        
        order_sql=''
        order_params=[]
        
        if order_field!='':
            try:
                order_field=int(order_field)
                order=int(order)
                
                if order_field>=0 and order_field<len(self.arr_order_fields):
                    order_sql='order by %s' % self.arr_order_fields[order_field]
                    if order>=0 and order<2:
                        order_sql+=' %s' % arr_order[order]
                    
                    #order_params=[self.arr_order_fields[order_field]]
                
            except:
                order_field=0
                order=0
                

        rows=[]
        
        with self.db.query(self.count_query, self.count_query_params) as cursor:
            total_elements=cursor.fetchone()['num_elements']
        
        str_query=self.str_query+' '+order_sql
        
        if self.limit>0:
            str_query+=' limit %s, %s'
        
        params=self.str_query_params
        params.append(begin_page)
        params.append(limit)
        
        with self.db.query(str_query, params) as cursor:
            for row in cursor:
                """
                c=len(self.arr_order_fields)
                for x in range(c, len(row)):
                    key_field=list(row.keys())[x]
                    #print(key_field)
                    pass
                """    
            
                for func_field in self.func_fields:
                    if func_field in row:
                        row[func_field]=self.func_fields[func_field](row[func_field], row)
            
                rows.append(row)                
                #{k:d[k] for  in set(d).intersection(l)}
            
        pages=Pages()
        
        html_pages=pages.show( begin_page, total_elements, limit, '#' ,initial_num_pages=self.initial_num_pages, variable='begin_page', label='', func_jscript='')
        
        return {'fields': self.fields, 'rows': rows, 'html_pages': I18n.lang('cuchulu', 'pages', 'Pages')+': '+html_pages}
        
        
    
    
