import json
import re
import os

import requests


class CodiMD:
    def __init__(self, server):
        self.login_cookies = None
        self.server_url = server

    def login(self, username, password, type='email'):
        if type == 'email':
            username_arg = "email"
            login_url = "login"
        elif type == 'ldap':
            username_arg = "username"
            login_url = "auth/ldap"
        else:
            raise NotImplementedError()

        r = requests.post("{}/{}".format(self.server_url, login_url), data={
            username_arg: username,
            'password': password
        })
        self.login_cookies = r.cookies
        print(self.login_cookies)

    def default_cookie_file(self):
        HOME = os.environ['HOME']
        XDG_CONFIG_HOME = os.environ.get('XDG_CONFIG_HOME', HOME + '/.config')
        CODIMD_CONFIG_DIR = os.environ.get('CODIMD_CONFIG_DIR', XDG_CONFIG_HOME + "/codimd")
        return os.environ.get('CODIMD_COOKIES_FILE', CODIMD_CONFIG_DIR + "/key.conf")

    def save_cookies(self, filename=None):
        if not filename: filename = self.default_cookie_file()
        raise NotImplementedError()

    def load_cookies(self, filename=None):
        # Will load cookies from the file specified as the parameter. The
        # format is compatible with the cookie-jar generated by libcurl,
        # therefor also codimd-cli,
        if not filename: filename = self.default_cookie_file()

        cookies = {}
        with open(filename, 'r') as fp:
            for line in fp:
                if not re.match(r'^\# ', line):
                    try:
                        lineFields = line.strip().split()
                        cookies[lineFields[5]] = lineFields[6]
                    except IndexError:
                        # This happens on an empty line
                        continue

        self.login_cookies = cookies

    def history(self):
        r = requests.get("{}/history".format(self.server_url),
                         cookies=self.login_cookies)
        return json.loads(r.text)['history']
