"""Renewable certificates storage."""
import datetime
import os
import re
import time

import configobj
import OpenSSL
import parsedatetime
import pytz
import pyrfc3339

from letsencrypt import constants
from letsencrypt import crypto_util
from letsencrypt import errors
from letsencrypt import le_util

ALL_FOUR = ("cert", "privkey", "chain", "fullchain")


def config_with_defaults(config=None):
    """Merge supplied config, if provided, on top of builtin defaults."""
    defaults_copy = configobj.ConfigObj(constants.RENEWER_DEFAULTS)
    defaults_copy.merge(config if config is not None else configobj.ConfigObj())
    return defaults_copy


def parse_time_interval(interval, textparser=parsedatetime.Calendar()):
    """Parse the time specified time interval.

    The interval can be in the English-language format understood by
    parsedatetime, e.g., '10 days', '3 weeks', '6 months', '9 hours', or
    a sequence of such intervals like '6 months 1 week' or '3 days 12
    hours'. If an integer is found with no associated unit, it is
    interpreted by default as a number of days.

    :param str interval: The time interval to parse.

    :returns: The interpretation of the time interval.
    :rtype: :class:`datetime.timedelta`"""

    if interval.strip().isdigit():
        interval += " days"
    return datetime.timedelta(0, time.mktime(textparser.parse(
        interval, time.localtime(0))[0]))


class RenewableCert(object):  # pylint: disable=too-many-instance-attributes
    """Renewable certificate.

    Represents a lineage of certificates that is under the management
    of the Let's Encrypt client, indicated by the existence of an
    associated renewal configuration file.

    Note that the notion of "current version" for a lineage is
    maintained on disk in the structure of symbolic links, and is not
    explicitly stored in any instance variable in this object. The
    RenewableCert object is able to determine information about the
    current (or other) version by accessing data on disk, but does not
    inherently know any of this information except by examining the
    symbolic links as needed. The instance variables mentioned below
    point to symlinks that reflect the notion of "current version" of
    each managed object, and it is these paths that should be used when
    configuring servers to use the certificate managed in a lineage.
    These paths are normally within the "live" directory, and their
    symlink targets -- the actual cert files -- are normally found
    within the "archive" directory.

    :ivar str cert: The path to the symlink representing the current
        version of the certificate managed by this lineage.
    :ivar str privkey: The path to the symlink representing the current
        version of the private key managed by this lineage.