'''
Created on Jun 8, 2014

@author: jvazquez
'''
import json

from organization import app
from organization.common.constants import JSON_HEADER

from .constants import AUTH_URL, FIXTURE_KEY, HEADER_SET_COOKIE, \
    HEADER_SPLIT_PATTERN, LOGIN_CHALLENGE, LOGIN_KEY


class UserTestToolChain(object):
    '''
    Provides an object that takes care of the
    minimal required funcionalities for all the
    modules in this application
    '''

    def __init__(self):
        '''
        Constructor
        '''
        pass

    def set_user_helper(self, user_helper):
        '''
        Inject an user helper object that contains
        the proper fixture data to obtain access
        to the system

        params:
            user_helper: FixtureHelper:UserHelper
        '''

        self.user_helper = user_helper

    def provide_login_credential(self, flask_client):
        '''
        Obtain a hash that can be used with flask
        test client to authenticate a request
        '''

        username = self.user_helper.data[FIXTURE_KEY][2][LOGIN_KEY]
        password = self.user_helper.data[FIXTURE_KEY][2][LOGIN_CHALLENGE]
        payload = json.dumps({LOGIN_KEY: username,
                              LOGIN_CHALLENGE: password})
        msg = "Using {username} and {password}".format(username=username,
                                                       password=password)
        app.logger.debug(msg)
        response = flask_client.post(AUTH_URL, data=payload,
                content_type=JSON_HEADER)
        sessionid = response.headers[HEADER_SET_COOKIE]\
            .split(HEADER_SPLIT_PATTERN)[0]
        return sessionid
