# Path: amgut/lib/util.py
# def make_survey_class(group, survey_type):
#     """Creates a form class for a group of questions
# 
#     The top-level attributes of the generated class correspond to the
#     question_ids from amgut.lib.human_survey_supp structures
# 
#     Select fields are generated for questions that require a single response,
#     and sets of checkboxes for questions that can have multiple responses
#     """
#     attrs = {}
#     prompts = {}
#     triggers = defaultdict(list)
#     triggered = defaultdict(list)
# 
#     for q in group.questions:
#         for eid, element in zip(q.interface_element_ids, q.interface_elements):
#             attrs[eid] = element
#             prompts[eid] = q.question
# 
#             if q.triggers:
#                 for triggered_id, triggering_responses in q.triggers.items():
#                     triggers[eid].extend(triggering_responses)
#                     triggered[eid].extend(group.id_to_eid[triggered_id])
# 
#     attrs['prompts'] = prompts
#     attrs['triggers'] = triggers
#     attrs['triggered'] = triggered
#     attrs['supplemental_eids'] = group.supplemental_eids
# 
#     return type(survey_type, (Form,), attrs)
# 
# def store_survey(survey, survey_id):
#     """Store the survey
# 
#     Parameters
#     ----------
#     survey : amgut.lib.data_access.survey.Survey
#         The corresponding survey
#     survey_id : str
#         The corresponding survey ID to retreive from redis
#     """
#     def get_survey_question_id(key):
#         return int(key.split('_')[-2])
# 
#     data = redis.hgetall(survey_id)
#     to_store = PartitionResponse(survey.question_types)
#     consent_details = loads(data.pop('consent'))
# 
#     if 'existing' in data:
#         data.pop('existing')
# 
#     for page in data:
#         page_data = loads(data[page])
#         questions = page_data['questions']
# 
#         for quest, resps in viewitems(questions):
#             qid = get_survey_question_id(quest)
#             qtype = survey.question_types[qid]
# 
#             if resps is None:
#                 resps = {-1}  # unspecified multiple choice
#             elif qtype in ['SINGLE', 'MULTIPLE']:
#                 resps = set([int(i) for i in resps])
#             else:
#                 pass
# 
#             to_store[qid] = resps
# 
#     with_fk_inserts = []
#     for qid, indices in viewitems(to_store.with_fk):
#         question = survey.questions[qid]
# 
#         for idx in indices:
#             resp = question.responses[idx] if idx != -1 else survey.unspecified
#             with_fk_inserts.append((survey_id, qid, resp))
# 
#     without_fk_inserts = [(survey_id, qid, dumps(v))
#                           for qid, v in viewitems(to_store.without_fk)]
# 
#     survey.store_survey(consent_details, with_fk_inserts, without_fk_inserts)


from urllib import urlencode
from tornado.escape import url_unescape
from json import dumps
from tornado.web import authenticated
from amgut.handlers.base_handlers import BaseHandler
from amgut.lib.survey_supp import (
    fermented_survey, surf_survey, personal_microbiome_survey)
from amgut.lib.util import make_survey_class, store_survey
from amgut.connections import ag_data, redis
from amgut import text_locale, media_locale
        survey_class = make_survey_class(sec_survey.groups[0],
                                         survey_type='SecondarySurvey')

        form = survey_class()
        if survey_id:
            form.process(data=sec_survey.fetch_survey(survey_id))

        # load existing information into the form
        if survey_id != '':
            data = sec_survey.fetch_survey(survey_id)
            form = survey_class(data=data)

        self.render('secondary_survey.html', skid=skid,
                    the_form=form, survey_id=survey_id,
                    type=survey_type, participant_name=participant_name)

    @authenticated
    def post(self):
        skid = self.current_user
        tl = text_locale['handlers']
        ag_login_id = ag_data.get_user_for_kit(skid)
        survey_id = self.get_argument('survey_id', None)
        survey_type = self.get_argument('type')
        participant_name = url_unescape(self.get_argument('participant_name'))
        sitebase = media_locale['SITEBASE']

        if not survey_id:
            survey_id = ag_data.get_new_survey_id()

        sec_survey = self.sec_surveys[survey_type]

# Path: amgut/lib/util.py
# def make_survey_class(group, survey_type):
#     """Creates a form class for a group of questions
# 
#     The top-level attributes of the generated class correspond to the
#     question_ids from amgut.lib.human_survey_supp structures
# 
#     Select fields are generated for questions that require a single response,
#     and sets of checkboxes for questions that can have multiple responses
#     """
#     attrs = {}
#     prompts = {}
#     triggers = defaultdict(list)
#     triggered = defaultdict(list)
# 
#     for q in group.questions:
#         for eid, element in zip(q.interface_element_ids, q.interface_elements):
#             attrs[eid] = element
#             prompts[eid] = q.question
# 
#             if q.triggers:
#                 for triggered_id, triggering_responses in q.triggers.items():
#                     triggers[eid].extend(triggering_responses)
#                     triggered[eid].extend(group.id_to_eid[triggered_id])
# 
#     attrs['prompts'] = prompts
#     attrs['triggers'] = triggers
#     attrs['triggered'] = triggered
#     attrs['supplemental_eids'] = group.supplemental_eids
# 
#     return type(survey_type, (Form,), attrs)
# 
# def store_survey(survey, survey_id):
#     """Store the survey
# 
#     Parameters
#     ----------
#     survey : amgut.lib.data_access.survey.Survey
#         The corresponding survey
#     survey_id : str
#         The corresponding survey ID to retreive from redis
#     """
#     def get_survey_question_id(key):
#         return int(key.split('_')[-2])
# 
#     data = redis.hgetall(survey_id)
#     to_store = PartitionResponse(survey.question_types)
#     consent_details = loads(data.pop('consent'))
# 
#     if 'existing' in data:
#         data.pop('existing')
# 
#     for page in data:
#         page_data = loads(data[page])
#         questions = page_data['questions']
# 
#         for quest, resps in viewitems(questions):
#             qid = get_survey_question_id(quest)
#             qtype = survey.question_types[qid]
# 
#             if resps is None:
#                 resps = {-1}  # unspecified multiple choice
#             elif qtype in ['SINGLE', 'MULTIPLE']:
#                 resps = set([int(i) for i in resps])
#             else:
#                 pass
# 
#             to_store[qid] = resps
# 
#     with_fk_inserts = []
#     for qid, indices in viewitems(to_store.with_fk):
#         question = survey.questions[qid]
# 
#         for idx in indices:
#             resp = question.responses[idx] if idx != -1 else survey.unspecified
#             with_fk_inserts.append((survey_id, qid, resp))
# 
#     without_fk_inserts = [(survey_id, qid, dumps(v))
#                           for qid, v in viewitems(to_store.without_fk)]
# 
#     survey.store_survey(consent_details, with_fk_inserts, without_fk_inserts)


# Path: amgut/handlers/secondary_survey.py
from urllib import urlencode
from tornado.escape import url_unescape
from json import dumps
from tornado.web import authenticated
from amgut.handlers.base_handlers import BaseHandler
from amgut.lib.survey_supp import (
    fermented_survey, surf_survey, personal_microbiome_survey)
from amgut.lib.util import make_survey_class, store_survey
from amgut.connections import ag_data, redis
from amgut import text_locale, media_locale

        survey_class = make_survey_class(sec_survey.groups[0],
                                         survey_type='SecondarySurvey')

        form = survey_class()
        if survey_id:
            form.process(data=sec_survey.fetch_survey(survey_id))

        # load existing information into the form
        if survey_id != '':
            data = sec_survey.fetch_survey(survey_id)
            form = survey_class(data=data)

        self.render('secondary_survey.html', skid=skid,
                    the_form=form, survey_id=survey_id,
                    type=survey_type, participant_name=participant_name)

    @authenticated
    def post(self):
        skid = self.current_user
        tl = text_locale['handlers']
        ag_login_id = ag_data.get_user_for_kit(skid)
        survey_id = self.get_argument('survey_id', None)
        survey_type = self.get_argument('type')
        participant_name = url_unescape(self.get_argument('participant_name'))
        sitebase = media_locale['SITEBASE']

        if not survey_id:
            survey_id = ag_data.get_new_survey_id()

        sec_survey = self.sec_surveys[survey_type]

        survey_class = make_survey_class(sec_survey.groups[0],