/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.cryptolib.certificates.bean;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.scytl.cryptolib.api.exceptions.GeneralCryptoLibException;
import com.scytl.cryptolib.certificates.constants.X509CertificateConstants;
import com.scytl.cryptolib.commons.utils.validations.Validate;

/**
 * Container class for dates of validity.
 */
public class ValidityDates {

    private final Date _startDate;

    private final Date _endDate;

    /**
     * Constructor which takes the starting and ending dates of validity as
     * input. Both of these dates are included in the period of validity.
     * 
     * @param startDate
     *            the starting date of validity, inclusive.
     * @param endDate
     *            the ending date of validity, inclusive.
     * @throws GeneralCryptoLibException
     *             if the dates are invalid.
     */
    public ValidityDates(final Date startDate, final Date endDate)
            throws GeneralCryptoLibException {

        validateInput(startDate, endDate);

        _startDate = new Date(startDate.getTime());
        _endDate = new Date(endDate.getTime());
    }

    /**
     * Retrieves the starting date of validity.
     * 
     * @return the starting date of validity.
     */
    public Date getNotBefore() {

        return new Date(_startDate.getTime());
    }

    /**
     * Retrieves the ending date of validity.
     * 
     * @return the ending date of validity.
     */
    public Date getNotAfter() {

        return new Date(_endDate.getTime());
    }

    private void validateInput(final Date startDate, final Date endDate)
            throws GeneralCryptoLibException {

        Validate.notNull(startDate, "Starting date of validity");
        Validate.notNull(endDate, "Ending date of validity");
        Validate.isBefore(startDate, endDate, "Starting date of validity",
            "ending date of validity");

        SimpleDateFormat formatter =
            new SimpleDateFormat("dd-M-yyyy hh:mm:ss", Locale.ENGLISH);
        String maxDateAsString =
            "31-12-"
                + X509CertificateConstants.X509_CERTIFICATE_MAXIMUM_VALIDITY_DATE_YEAR
                + " 23:59:59";
        Date maxDate;
        try {
            maxDate = formatter.parse(maxDateAsString);
        } catch (ParseException e) {
            throw new GeneralCryptoLibException(
                "Could not convert to Date object from String format", e);
        }

        Validate.isBefore(startDate, maxDate, "Starting date of validity",
            "maximum date of validity");
        Validate.isBefore(endDate, maxDate, "Ending date of validity",
            "maximum date of validity");
    }
}
