import hashlib
import os
import re
import urllib2
from djrandom_client import version

NESTING = 2
VERSION_PY_URL = 'https://git.autistici.org/djrandom/plain/client/djrandom_client/version.py'


def generate_path(base_dir, sha1):
    dir_parts = [base_dir]
    dir_parts.extend(sha1[:NESTING])
    base_path = os.path.join(*dir_parts)
    if not os.path.isdir(base_path):
        os.makedirs(base_path)
    return os.path.join(base_path, sha1)


def sha1_of_file(path):
    with open(path, 'rb') as fd:
        sha = hashlib.sha1()
        while True:
            chunk = fd.read(4096)
            if not chunk:
                break
            sha.update(chunk)
        return sha.hexdigest()


class SyntaxError(Exception):
    pass


def _unquote(s):
    for qchar in ('"', '\''):
        if s.startswith(qchar) and s.endswith(qchar):
            return s.strip(qchar)
    return s


def read_config_defaults(parser, path):
    if not os.path.exists(path):
        return
    with open(path, 'r') as fd:
        for linenum, line in enumerate(fd):
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            if '=' not in line:
                raise SyntaxError('%s, line %d: Syntax Error' % (
                        path, 1 + linenum))
            var, value = map(lambda x: x.strip(), line.split('=', 1))
            parser.set_default(var, _unquote(value))


def _split_version_string(s):
    def _toint(x):
        try:
            return int(x)
        except:
            return x
    return tuple(map(_toint, s.split('.')))


def check_version():
    """Returns True if we need to upgrade."""
    try:
        last_version_str = urllib2.urlopen(VERSION_PY_URL).read()
    except:
        return False

    match = re.match(r'VERSION\s*=\s*[\'"]([0-9a-z.]+)[\'"]',
                     last_version_str.strip())
    if not match:
        return False
    last_version_t = _split_version_string(match.group(1))
    cur_version_t = _split_version_string(version.VERSION)

    return cur_version_t <= last_version_t