# -*- 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(s
urvey=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.s