import pycurl
import os
from io import BytesIO
from urllib.parse import urlencode
from json import loads

# setting up variables
response = BytesIO()


def get_hypothesis(answers):
    """function for calling NPS with andswers to consultation questions

    Args:
        answers (list): users answers to questions

    Returns:
        list: list of hypothesis results where criteria for filtering phones are set
    """
    # loading enviroment variables with data to login to NPS
    email = os.environ.get('NPS_EMAIL')
    psw = os.environ.get('NPS_PSW')
    # activating curl session
    crl = pycurl.Curl()
    # logging into NPS and getting JWT token
    data_login = {'_email': '%s' % email,
                  '_password': '%s' % psw}
    data_login_url = urlencode(data_login)
    # set url value
    crl.setopt(crl.URL, 'https://www.stud.feec.vutbr.cz/~xkorin12/npsdata/login')
    # something about certificates doesn§t work without it
    crl.setopt(pycurl.SSL_VERIFYPEER, 1)
    crl.setopt(pycurl.SSL_VERIFYHOST, 2)
    crl.setopt(pycurl.CAINFO, r"cacert.pem")

    # write bytes that are utf-8 encoded
    crl.setopt(crl.POSTFIELDS, data_login_url)
    # perform a file transfer
    response = crl.perform_rb()
    # get a token from rensponse body
    res = loads(response)
    token = res['token']

    # activating base and sending all answers at once
    base_id = 5642
    crl.setopt(
        crl.URL, 'https://www.stud.feec.vutbr.cz/~xkorin12/npsdata/feedback/do?lang=cs-CZ')
    # setting up query header it uses authorization token acquired before
    crl.setopt(crl.HTTPHEADER, ['X-Requested-With: XMLHttpRequest',
                                'Authorization: Bearer %s' % token, 'Content-Type: application/x-www-form-urlencoded'])
    # setting up data for query, answer is set for every question in knowlage base, all answers are send together
    data_to_send = {'baseId': '%s' % base_id, 'answers[video]': '%s' % answers[0]['value'], 'answers[hry]': '%s' % answers[1]['value'], 'answers[fotak]': '%s' % answers[2]['value'], 'answers[sport]': '%s' % answers[3]['value'],
                    'answers[baterka]': '%s' % answers[4]['value'], 'answers[dualsim]': '%s' % answers[5]['value'], 'answers[pamet]': '%s' % answers[6]['value'], 'answers[odolnost]': '%s' % answers[7]['value']}
    # encode data
    data_to_send_url = urlencode(data_to_send)
    # write bytes that are utf-8 encoded
    crl.setopt(crl.POSTFIELDS, data_to_send_url)
    # perform a file transfer
    result_hypothesis = loads(crl.perform_rs())
    # end curl session
    crl.close()

    return(result_hypothesis)
