#include "sender.h"

#include <stdexcept>

#include "json.hpp"

#include "expiring_signature.h"

namespace BareMinimumCrypto {
	using nlohmann::json;
	
	optional <Sender> Sender::create (SigningKey k, ExpiringSignature c)
	{
		Sender s;
		s.sender_key = k;
		s.cert = c;
		
		return s;
	}
	
	Bytes Sender::try_sign (const Bytes & data, Instant now) const {
		const auto signed_data = std::move (*sender_key.sign_data (data, now));
		
		const json j {
			{"cert", {
				{"sig", json::binary (cert.sig)},
				{"cert", json::binary (cert.cert)},
			}},
			{"data", {
				{"sig", json::binary (signed_data.sig)},
				{"cert", json::binary (signed_data.cert)},
			}},
		};
		
		return json::to_msgpack (j);
	}
	
	optional <Bytes> Sender::sign (const Bytes & data, Instant now) const {
		try {
			return try_sign (data, now);
		}
		catch (exception &) {
			return nullopt;
		}
	}
	
	optional <Bytes> Sender::sign (const Bytes & data) const {
		return sign (data, Instant::now ());
	}
}