# -*- coding: utf-8 -*-
#loadmodelcontroller
"""Survey Controller"""

from tg import expose, flash, require, url, lurl, request, redirect, tmpl_context,validate,session
from tg.i18n import ugettext as _, lazy_ugettext as l_
from tg.exceptions import HTTPFound
from tg import predicates
from pollandsurvey import model
#from pollandsurvey.controllers.secure import SecureController
#from pollandsurvey.model import DBSession, metadata
#from tgext.admin.tgadminconfig import BootstrapTGAdminConfig as TGAdminConfig
#from tgext.admin.controller import AdminController
from pollandsurvey.lib.base import BaseController
#from pollandsurvey.controllers.error import ErrorController
from surveyobject import SearchObject
import sys;
import json
from tg.configuration import config

from pollandsurvey.service import VoterService
from pollandsurvey.service import OptionService
from tgext.pyutilservice import ManageSession, Utility, VoterDataMapType, extraLog
import logging;
from surveyobject.jsontoobject import JsontoObject

log = logging.getLogger(__name__);
from tgext.pylogservice import LogDBHandler, exception
__all__ = ['ScriptModelController']
class ScriptModelController(BaseController):

    def __init__(self):
        self.utility = Utility();
        dh = LogDBHandler( config=config,request=request);
        log.addHandler(dh)

        self.voterservice = VoterService(mymodel = model)
        self.optionservice = OptionService(mymodel = model)
    @expose()
    def index(self, came_from=lurl('/')):
        if not request.identity:
            login_counter = request.environ.get('repoze.who.logins', 0) + 1
            redirect('/login',
                params=dict(came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)

        # Do not use tg.redirect with tg.url as it will add the mountpoint
        # of the application twice.
        return HTTPFound(location=came_from)
    
    @expose('json')
    def getQuestionType(self, *args, **kw):
       # questiontype = model.QuestionType.getAll(1);
        questiontype = model.QuestionType.getByProjectType(kw.get('projecttypeid'))#.getAll(1);
        return dict(survey=questiontype , total = len(questiontype));

    @expose('json')
    def getBasicData(self, *args, **kw):
        self.searchObject = SearchObject(**kw)
        basicQuestion = model.BasicQuestion.getBasicTextById(self.searchObject.idsearch);
        basicQuestion= model.BasicQuestion.convertBasicTextToJson(basicQuestion);
        return dict(survey=basicQuestion , total = len(basicQuestion));

    @expose('json')
    def getBasicMediaData(self, *args, **kw):
        BasicQuestion = model.BasicQuestion.getBasicMediaById(kw.get('questionid'));
        BasicQuestion= model.BasicQuestion.convertBasicTextToJson(BasicQuestion);
        return dict(survey=BasicQuestion , total = len(BasicQuestion));

    @expose('json')
    def getQuestionsData(self, *args, **kw):
        self.searchObject = SearchObject(**kw)
        print "keysearch = %s" %self.searchObject.keysearch
        question = model.Question.getQuestionByGroupId(self.searchObject.keysearch);      
        return dict(survey=question , total = len(question));

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def removeGroupQuestion(self,  *args, **kw):
        self.questionGroup =  json.loads(request.body, encoding=request.charset, object_hook=model.QuestionGroup.setId)
        self.message = ""
        self.status = True
        if(self.questionGroup):
            self.questions = model.Question.getQuestionByGroupId(self.questionGroup.id_question_group)
            if(self.questions and len(self.questions) > 0 ):
                log.info("can not delete " , extra=extraLog());
                self.message = "Cann't delete. Please delete all questions."
                self.status = False
        return dict(sucess= self.status, message = self.message);

    @expose('json')
    def getOptionsProject(self, *args, **kw):
        question = []
        total=0
        try :
            self.searchObject = SearchObject(**kw)
            question,total = self.optionservice.getListOption(searchObject=self.searchObject)
        except Exception as e:
            log.info("getOptionsProject" , extra=extraLog());
        return dict(survey=question , total = total);

    @expose('json')
    def getOptionTheme(self, *args, **kw):
        question = model.QuestionTheme.getAll(1);
        return dict(survey=question , total = len(question));

    @expose('json')
    def getDefficultyLevel(self, *args, **kw):
        question = model.DifficultyLevel.getAll(1);
        return dict(survey=question , total = len(question));

    @expose('json')
    def getCloseType(self, *args, **kw):
        question = model.CloseType.getAll(1);
        return dict(survey=question , total = len(question));

    @expose('json')
    def getRandomType(self, *args, **kw):
        question = model.RandomType.getAll(1);
        return dict(survey=question , total = len(question));

    @expose('json')
    def getLanguages(self,*args, **kw):
        languages = model.Languages.getAll();
        return dict(survey=languages,total=len(languages));

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getEmailVoters(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        user =  request.identity['user'];
        question=[]
        question=model.Voter.getVoterByEmailUser(email=kw['email'], userid=user.user_id)
        return dict(survey=question);

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getVotersDataAccessControl(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");        
        question=[]
        total=0
        try :
            user =  request.identity['user'];
            self.searchObject = SearchObject(**kw)
            if (str(self.searchObject.idsearch) == str(VoterDataMapType.voter.value)):
                question, total = model.VoterMapProject.getListByProject(idproject=self.searchObject.keysearch, page=int(self.searchObject.page)-1, page_size=int(self.searchObject.limit))
            else :
                question, total = model.Voter.getListVoterByVoterType(user_id_owner=user.user_id, voter_type=self.searchObject.idsearch, page=int(self.searchObject.page)-1 ,page_size=int(self.searchObject.limit))
        except Exception as e:
            log.info("getVotersDataAccessControl" , extra=extraLog());        
        return dict(survey=question , total = total);

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getInvitationData(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        question=[]
        total=0
        try :
            self.searchObject = SearchObject(**kw)
            user =  request.identity['user'];
            question,total = model.Invitation.getByUser(userid = user.user_id, page=int(self.searchObject.page)-1 ,  page_size=int(self.searchObject.limit));
        except Exception as e:
            log.info("getInvitationData" , extra=extraLog());        
        return dict(survey=question , total = total);

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getDataProfileField(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.question = [];
        self.question = model.MapDataProfileGroupField.getQueryByDataProfileField()
        #for data in self.dataProfileField :
        #    question.append(data.to_json())
        return dict(survey=self.question , total = len(self.question));

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getInvitationNumberData(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        question=[]
        total=0
        try :
            user =  request.identity['user'];
            self.searchObject = SearchObject(**kw)
            result,question,total = model.SendMail.getInvitationNumberByPublicId(idpublic=self.searchObject.idsearch, page=int(self.searchObject.page)-1, page_size=int(self.searchObject.limit));
        except Exception as e:
            log.info("getInvitationNumberData" , extra=extraLog());
        return dict(survey=question , total = total);

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getListTrackVosterData(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        question=[]
        total=0
        try :
            user =  request.identity['user'];
            self.searchObject = SearchObject(**kw)
            result,question,total = model.Respondents.getListByPublicId(idpublic=self.searchObject.idsearch ,page=int(self.searchObject.page)-1 ,  page_size=int(self.searchObject.limit));
        except Exception as e:
            log.info("getListTrackVosterData" , extra=extraLog());
        return dict(survey=question , total = total);
    
    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getProjectById(self,  *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.searchObject = SearchObject(**kw)
        print kw
        quest_project = []
        total = 0
        if request.identity:
            user =  request.identity['user'];
            quest_project, total = model.QuestionProject.getAllByProjectUser(1,user.user_id,self.searchObject.keysearch, page= 0, page_size = 1)
        log.info("getProjectById" , extra=extraLog());
        return dict(survey=quest_project , total = total);
     
    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getProjectByUser(self,  *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        quest_project = []
        total = 0
        print kw
        try :
            self.searchObject = SearchObject(**kw)
            if request.identity:
                user =  request.identity['user'];
                quest_project,total = model.QuestionProject.getAllByUser(1,user.user_id, page= int(self.searchObject.page)-1, page_size = int(self.searchObject.limit));
        except Exception as e:        
            log.info("getProjectByUser" , extra=extraLog());
        return dict(survey=quest_project , total = total);
    
    @expose('json')
    #@require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getProjectByUserTong(self,  *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        print "access : get Project by user tong"
        print args
        print kw
        quest_project = []
        total = 0

        try :
            self.searchObject = SearchObject(**kw)
            #if request.identity:
                #user =  request.identity['user'];
            quest_project,total = model.QuestionProject.getAllByUser(1,3, page= int(self.searchObject.page)-1, page_size = int(self.searchObject.limit));
        except Exception as e:        
            log.info("getProjectByUser" , extra=extraLog());
            
        return dict(survey=quest_project , total = total);
    
    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getGroupQuestionByUser(self,  *args, **kw):
        reload(sys).setdefaultencoding("utf-8");        
        self.searchObject = SearchObject(**kw) 
        group_question =[];  
        self.total =0;      
        if request.identity:
            user =  request.identity['user']; 
            group_question, self.total = model.QuestionGroup.getByProjectId(self.searchObject.keysearch, user.user_id);             
        return dict(survey=group_question , total = self.total); 
    
    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getDefaultEmailTemplate(self,  *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.emailtemplate = model.EmailTemplate.getTemplateBy(5);
        self.template = [];
        self.template.append(self.emailtemplate);
        return dict(survey=self.template , total = len(self.template)); 
    
    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getResult_old(self,  *args, **kw):
        reload(sys).setdefaultencoding("utf-8")
        self.searchObject = SearchObject(**kw)
        self.result, self.total = model.QuestionResult.getByResultQuestionGroupId(self.searchObject.keysearch,self.searchObject.idsearch)
        return dict(survey=self.result , total = self.total); 
    
    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getResult(self,  *args, **kw):
        reload(sys).setdefaultencoding("utf-8")
        self.searchObject = SearchObject(**kw)
        self.result, self.total = model.QuestionResult.getByResultGroupId(groupid=self.searchObject.idsearch,page= int(self.searchObject.page)-1, page_size = int(self.searchObject.limit));
        return dict(survey=self.result , total = self.total); 
    
    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getResultGroup(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.searchObject = SearchObject(**kw)       
        self.resultgroup, self.total = model.QuestionResultGroup.getByProjectId(projectid=self.searchObject.idsearch,page= int(self.searchObject.page)-1, page_size = int(self.searchObject.limit));          
        return dict(survey=self.resultgroup , total = self.total); 

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getQuestionNumber(self,**kw):
        reload(sys).setdefaultencoding('utf8')
        self.total=0       
        try :
            self.total = model.Question.getQuestionNumber(kw.get('idproject'));
        except Exception as e:
            log.info("getQuestionNumber" , extra=extraLog());
        return dict(total = self.total);

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getGroupQuestionAmount(self,**kw):
        reload(sys).setdefaultencoding("utf-8");      
        self.getamount_data=[]
        self.total=0  
        try :
            self.searchObject = SearchObject(**kw)
            #self.getamount_data = self.optionservice.getAmountData(searchObject=self.searchObject)        
            self.getamount_data, self.total = model.QuestionGroup.getAmountSummaryForGrouping(idproject=self.searchObject.keysearch, idoption=self.searchObject.idsearch)
        except Exception as e:
            log.info("getGroupQuestionAmount" , extra=extraLog());
        return dict(survey=self.getamount_data , total=self.total);

    @expose('json')
    def getMarriageStatus(self,*args, **kw):
        marriagestatus = model.MarriageStatus.getAll(1);
        return dict(survey=marriagestatus , total = len(marriagestatus));    

    @expose('json')
    def getContentForHelp(self,**kw):
        reload(sys).setdefaultencoding("utf-8");
        self.searchObject = SearchObject(**kw)
        self.content = model.Content.getByContentType(self.searchObject.idsearch,lang=ManageSession.getLanguage())
        self.value =""
        if self.content:
            self.value = self.content.content
        return dict(content = self.value)

    @expose('json')
    def getPasswordType(self,*args,**kw):
        reload(sys).setdefaultencoding("utf-8");
        password_type = model.PasswordType.getAll(1);
        return dict(survey=password_type , total = len(password_type));

    @expose('json')
    def getVoterType(self,*args,**kw):
        reload(sys).setdefaultencoding("utf-8");
        voter_type = model.VoterType.getAll(1);
        return dict(survey=voter_type , total = len(voter_type));

    @expose('json')
    def getQuestionGeneralInformation(self,*args,**kw):
        reload(sys).setdefaultencoding("utf-8");
        self.searchObject = SearchObject(**kw)
        self.result = model.QuestionGeneralInformation.getByProject(self.searchObject.idsearch)
        self.value = []
        for d in self.result:
            self.value.append(d.toJsonView())
        return dict(survey= self.value , total = len(self.value));    

    @expose('json')
    def getAccessControl(self,*args,**kw):        
        reload(sys).setdefaultencoding("utf-8");
        acc = []
        total = 0
        try :
            self.searchObject = SearchObject(**kw)        
            acc,total = model.AccessControlGroup.getByProject(idproject = self.searchObject.idsearch,page=int(self.searchObject.page)-1,page_size=int(self.searchObject.limit));
        except Exception as e:
            log.info("getAccessControl" , extra=extraLog());        
        return dict(survey=acc , total = total);

    @expose('json')
    def getPageAccessControl(self,*args,**kw):
        reload(sys).setdefaultencoding('utf8')
        status = True
        self.success = True
        self.searchObject = SearchObject(**kw)
        self.accesscontrol=[]
        self.total=0
        page = 0
        self.idacc = self.searchObject.keysearch
        self.idproject = self.searchObject.idsearch
        while(status):
            self.accesscontrol,self.total = model.AccessControlGroup.getByProject(idproject = self.idproject,page=page,page_size=int(self.searchObject.limit));   
            for acc_list in self.accesscontrol:
                acc = JsontoObject(acc_list)
                if (acc.id_access_control_group == self.idacc):
                    status = False
                    break
            if(status):page = page+1
            if len(self.accesscontrol) == 0 :
                self.status = False
                page = 0
                break
        page = page+1
        return dict(success=self.success,page = page);

    @expose('json')
    def getPageEmailTemplate(self,*args,**kw):
        reload(sys).setdefaultencoding('utf8')
        status = True
        self.success = True
        page = 0
        self.searchObject = SearchObject(**kw)
        if request.identity:
            user =  request.identity['user']            
            self.invitation=[]
            self.total=0
            
            id_invitation = int(self.searchObject.keysearch);
            while(status):
                self.invitation,self.total = model.Invitation.getByUser(userid = user.user_id, page=page ,page_size=int(self.searchObject.limit));
                for emailtemplate in self.invitation:
                    emailTemplate = JsontoObject(emailtemplate)
                    if(emailTemplate.id_question_invitation == id_invitation):
                        status = False
                        break
                if(status):page = page+1
                if len(emailtemplate) == 0:
                    status = False
                    page = 0
                    break
            page = page+1
        return dict(success=self.success,page = page);

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getMapVotersAccessControl(self,*args,**kw):
        reload(sys).setdefaultencoding("utf-8");
        survey=[]
        total=0
        try :
            self.searchObject = SearchObject(**kw)
            survey,total = model.MapAccessControlVoter.getByAccessControl(idacc = self.searchObject.idsearch,page=int(self.searchObject.page)-1,page_size=int(self.searchObject.limit));
        except Exception as e:
            log.info("getMapVotersAccessControl" , extra=extraLog());
        return dict(survey=survey , total = total);

    @expose('json')
    def getCheckAccessControlMapVoter(self,*args,**kw):
        reload(sys).setdefaultencoding('utf8');
        self.searchObject = SearchObject(**kw)
        self.success = False;
        self.mapvoter=[]
        self.mapvoter = model.MapAccessControlVoter.getCheckAccessControl(idvoter=self.searchObject.idsearch, idacc=self.searchObject.keysearch)
        if len(self.mapvoter) == 0 :
            self.success = True;
        return dict(success=self.success);

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getContactData(self,*args,**kw):
        reload(sys).setdefaultencoding("utf-8");
        contact = []
        total = 0
        try :
            self.searchObject = SearchObject(**kw)
            user =  request.identity['user'];            
            contact,total = model.VoterMapType.getListVoterByOwner(voter_type=str(VoterDataMapType.contact.value) ,user_id_owner = user.user_id, page=int(self.searchObject.page)-1 ,page_size=int(self.searchObject.limit));
        except Exception as e:
            log.info("getContactData" , extra=extraLog());
        return dict(survey=contact , total = total);

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getVotersData(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");        
        question=[]
        total=0
        try :
            user =  request.identity['user'];
            self.searchObject = SearchObject(**kw)        
            question,total = model.VoterMapProject.getListByProject(idproject=self.searchObject.idsearch, page=int(self.searchObject.page)-1, page_size=int(self.searchObject.limit))
        except Exception as e:
            log.info("getVotersData" , extra=extraLog());
        return dict(survey=question , total = total);

    @expose('json')
    def getVoterImportData(self,*args,**kw):        
        reload(sys).setdefaultencoding("utf-8");        
        contact=[]
        total=0    
        try :            
            self.searchObject = SearchObject(**kw)
            contact, total = self.voterservice.getVoterImport(searchObject = self.searchObject);            
        except Exception as e:            
            log.info("getVoterImportData" , extra=extraLog());
        return dict(survey=contact, total=total);

    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getProjectLanguagesById(self,*args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.message = ""
        self.status = True
        self.searchObject = SearchObject(**kw)
        user =  request.identity['user']
        self.survey = []
        self.mapQuestionProjectLanguage, self.total = model.MapQuestionProjectLanguage.getbyProjectId(id_question_project = self.searchObject.idsearch,
                                                                    userid = user.user_id, 
                                                                    page= int(self.searchObject.page)-1, 
                                                                    page_size = int(self.searchObject.limit))        
        for self.maplang in self.mapQuestionProjectLanguage:
            self.survey.append({
                                'id_map_question_project_language' : self.maplang.id_map_question_project_language,
                                'id_question_project' : self.maplang.id_question_project,
                                'id_language' : self.maplang.id_language,
                                'is_default' : self.maplang.is_default,
                                'language' : self.maplang.language.name
            })
        return dict(survey=self.survey , total = self.total)    
    
    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getQuestionLanguagesByMapId(self,*args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.message = ""
        self.status = True
        searchObject = SearchObject(**kw)
        user =  request.identity['user']
        self.mapQuestionLanguage = model.MapQuestionProjectLanguage.getId(searchObject.idsearch)
        questionlang = []
        if(self.mapQuestionLanguage):
            result = model.Question.getQuestionByLang(id_project = self.mapQuestionLanguage.id_question_project ,id_language = self.mapQuestionLanguage.id_language)
            for question,questionLanguage in result:
                obj = {'id_question': '', 'question': '' , 'help_message':'', 'text_label':'', 'id_language':self.mapQuestionLanguage.id_language, 'question_lang':'', 'help_message_lang':'','text_label':'' }
                if question :
                    obj['id_question'] = question.id_question
                    obj['question'] = question.question
                    obj['help_message'] = question.help_message
                    obj['text_label'] = question.text_label
                if questionLanguage :
                    obj['id_language'] = questionLanguage.id_language  
                    obj['question_lang'] = questionLanguage.question
                    obj['help_message_lang'] = questionLanguage.help_message
                    obj['text_label'] = questionLanguage.text_label
                del question,questionLanguage                
                questionlang.append(obj)
            del result
        del searchObject, self.mapQuestionLanguage, self.message, self.status
        return dict(survey =  questionlang , total = len(questionlang))
        
    @expose('json')
    @require(predicates.in_any_group('voter','managers', msg=l_('Only for voter')))
    def getBasicDataLanguages(self,*args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        self.message = ""
        self.status = True
        self.searchObject = SearchObject(**kw)
        user =  request.identity['user']

        result = model.BasicQuestion.getByQuestionLang(id_question=self.searchObject.idsearch, id_language=self.searchObject.keysearch)
        basicDataLang = []
        for basicQuestion,basicTextData,basicTextDataLanguage in result:
            obj = {'id_question':'','id_basic_data':'','value':'','id_language': self.searchObject.keysearch, 'value_lang': ''}
            if basicQuestion:
                obj['id_question'] = basicQuestion.id_question
                obj['id_basic_data'] = basicQuestion.id_basic_data
            if basicTextData:
                obj['value'] = basicTextData.value
            if basicTextDataLanguage:
                obj['id_language'] = basicTextDataLanguage.id_language
                obj['value_lang'] = basicTextDataLanguage.value
            del basicQuestion, basicTextData, basicTextDataLanguage
            basicDataLang.append(obj)
        del result    
        return dict(survey =  basicDataLang , total = len(basicDataLang))
    
    @expose('json')
    def getLangByProject(self,*args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        searchObject = SearchObject(**kw)
        mapQuestionLanguage, total = model.MapQuestionProjectLanguage.getbyProjectId(id_question_project = searchObject.idsearch)
        questionLang = []
        for qLang in mapQuestionLanguage:
            obj = {'id_question_project': '' , 'id_language': '', 'is_default':0, 'code' : '', 'name_local': '' }
            obj['id_question_project'] = qLang.id_question_project
            obj['id_language'] = qLang.id_language
            obj['is_default'] = qLang.is_default
            if qLang.language:
                obj['code'] = qLang.language.code2
                obj['name_local'] = qLang.language.name_local
            questionLang.append(obj)
        del searchObject
        return dict(survey =  questionLang , total = total)
    
    @expose('json')
    def getQuestionLangByProject(self, *args, **kw):
        reload(sys).setdefaultencoding("utf-8");
        
        question = []
        question.append( {'id' : 468, 'lang' : {'en' : 'sample 1', 'th' : 'ตัวอย่าง'} , 'answer' : [{'id' : 120534, 'lang' : {'en' : 'sample 1', 'th' : 'ตัวอย่าง 1'}}, {'id' : 120535, 'lang' : {'en' : 'sample 2', 'th' : 'ตัวอย่าง 2'}}  ] })
        
        #question.append({468 : {'question' : {'en' : 'sample 1', 'th' : 'ตัวอย่าง'} , 'answer':[{120534 :  {'en' : 'sample 1', 'th' : 'ตัวอย่าง 1'}}, {120535 :  {'en' : 'sample 2', 'th' : 'ตัวอย่าง 2'}}  ] }})
        
        
        #{id:207, lang : {en: 'If 2x-y=4 then calculate 6x-3y=?',th:'ถ้า  2x-y=4 แล้ว 6x-3y=?'}}
        
        
        return dict(survey = question)
    
    @expose('json')
    def getDifficultyLevel(self):
        reload(sys).setdefaultencoding("utf-8");       
        self.level = model.DifficultyLevel.getAll(active=1)
        return dict(level=self.level, total=len(self.level))
    
    @expose('json')
    def getProjectType(self, *args, **kw):
        projectType = model.QuestionProjectType.getAll();
        self.type = []
        for ptype in projectType:
            self.type.append(dict(id = ptype.id_question_project_type, value = ptype.description) )
            
         
        return dict(survey=self.type , total = len(self.type));