import re

import click
from packaging.requirements import Requirement as _Requirement

from spaken.s3 import S3Storage

COMMENT_RE = re.compile(r'(^|\s)+#.*$')


class Requirement(_Requirement):

    def __eq__(self, other):
        return str(self) == str(other)


def get_storage_backend(uri):
    if uri.startswith('s3://'):
        return S3Storage(uri)
    else:
        raise click.UsageError(
            "Unsupported storage uri (only s3:// is for now)")


def parse_requirements(filename):
    packages = []
    options = []

    with open(filename, 'r') as fh:
        for line in _process_requirement_lines(fh):
            if line.startswith('-'):
                options.append(line)
            else:
                packages.append(Requirement(line))

    return packages, options


def _process_requirement_lines(fh):
    prev_line = None

    for line in fh:
        line = line.strip()

        # Remove comments
        line = COMMENT_RE.sub('', line)
        line = line.strip()

        # Skip empty lines
        if not line:
            continue

        if prev_line:
            line = prev_line + line

        if line.endswith('\\'):
            prev_line = line.rstrip('\\')
        else:
            prev_line = None
            yield line


def write_requirements(requirements, pip_arguments, path):
    with open(path, 'w') as fh:
        fh.write('# Generated by spaken for retrieving missing packages\n')
        fh.writelines(['%s\n' % req for req in pip_arguments])
        fh.writelines(['%s\n' % req for req in requirements if req])
