#!{{ python_executable }}

from IPython.kernel.zmq.kernelbase import Kernel
from IPython.core.display import HTML

import requests
import logging

erp5_url  = "{{ erp5_url }}"

class ERP5Kernel(Kernel):
    implementation = 'ERP5'
    implementation_version = '1.0'
    language = 'ERP5'
    language_version = '0.1'
    language_info = {'mimetype': 'text/plain', 'name':'python'}
    banner = "ERP5 integration with ipython notebook"

    def __init__(self, user=None, pwd=None, url=None, status_code=None,
                *args, **kwargs):
        super(ERP5Kernel, self).__init__(*args, **kwargs)
        self.user = user
        self.pwd = pwd
        self.url = erp5_url
        self.status_code = status_code

    def do_execute(self, code, silent, store_history=True, user_expressions=None,
            allow_stdin=False):
        if not silent:

            if code.startswith('%erp5_user'):
                self.user = code.split()[1]
                resp = 'Your erp5 username is %s' %self.user
                stream_content = {'name': 'stdout', 'text': resp}
                self.send_response(self.iopub_socket, 'stream', stream_content)

            elif code.startswith('%erp5_password'):
                self.pwd = code.split()[1]
                if self.user:
                    try:
                        # Dirty hack here just to send some random parameter
                        # Should be removed with better way to get 200 status code
                        # for correct credentials or yet better make 204 also accepatble

                        test = 'return test'
                        res = requests.get(self.url, verify=False,
                                          auth=(self.user, self.pwd),
                                          params={'python-expression': test})
                        self.status_code = res.status_code
                        if self.status_code != 200:
                            resp = 'Incorrect username or password'
                        else:
                            resp = 'Please proceed'
                    except requests.exceptions.RequestException as e:
                        resp = e
                else:
                     resp = 'Please enter your username in next cell'
                stream_content = {'name': 'stdout', 'text': resp}
                self.send_response(self.iopub_socket, 'stream', stream_content)

            else:
                if self.status_code == 200:
                    res = requests.get(self.url, verify=False,
                                      auth=(self.user, self.pwd),
                                      params={'python_expression': code})
                    code_result = res.text

                else:
                    code_result = 'Unauthorized access'

                data = {
                        'data': {'text/html': code_result},
                        'metadata': {}
                       }
                self.send_response(self.iopub_socket, 'display_data', data)

        return {'status': 'ok',
                    # The base class increments the execution count
                    'execution_count': self.execution_count,
                    'payload': [],
                    'user_expressions': {},
                    }

if __name__ == '__main__':
    from IPython.kernel.zmq.kernelapp import IPKernelApp
    IPKernelApp.launch_instance(kernel_class=ERP5Kernel)
else:
    from IPython.kernel.zmq.kernelapp import IPKernelApp