/*
 * Copyright 2014-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.session.data.mongo;

import org.springframework.lang.Nullable;
import org.springframework.session.Session;

import java.time.Duration;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Session object providing additional information about the datetime of expiration.
 *
 * @author Jakub Kubrynski
 * @author Greg Turnquist
 * @since 1.2
 */
public class MongoSession implements Session {

	/**
	 * Mongo doesn't support {@literal dot} in field names. We replace it with a unicode character from the Private Use Area.
	 * <p>
	 * NOTE: This was originally stored in unicode format. Delomboking the code caused it to get converted to another encoding,
	 * which isn't supported on all systems, so we migrated back to unicode. The same character is being represented ensuring
	 * binary compatibility.
	 *
	 * @see https://www.compart.com/en/unicode/U+F607
	 */
	private static final char DOT_COVER_CHAR = '\uF607';

	private String id;

	private String originalSessionId;

	private long createdMillis = System.currentTimeMillis();

	private long accessedMillis;

	private long intervalSeconds;

	private Date expireAt;

	private Map<String, Object> attrs = new HashMap<>();

	public MongoSession() {
		this(MongoIndexedSessionRepository.DEFAULT_INACTIVE_INTERVAL);
	}

	public MongoSession(long maxInactiveIntervalInSeconds) {
		this(UUID.randomUUID().toString(), maxInactiveIntervalInSeconds);
	}

	public MongoSession(String id, long maxInactiveIntervalInSeconds) {

		this.id = id;
		this.originalSessionId = id;
		this.intervalSeconds = maxInactiveIntervalInSeconds;
		setLastAccessedTime(Instant.ofEpochMilli(this.createdMillis));
	}

	static String coverDot(String attributeName) {
		return attributeName.replace('.', DOT_COVER_CHAR);
	}

	static String uncoverDot(String attributeName) {
		return attributeName.replace(DOT_COVER_CHAR, '.');
	}

	@Override
	public String changeSessionId() {

		String changedId = UUID.randomUUID().toString();
		this.id = changedId;
		return changedId;
	}

	@Override
	@Nullable
	public <T> T getAttribute(String attributeName) {
		return (T) this.attrs.get(coverDot(attributeName));
	}

	@Override
	public Set<String> getAttributeNames() {
		return this.attrs.keySet().stream().map(MongoSession::uncoverDot).collect(Collectors.toSet());
	}

	@Override
	public void setAttribute(String attributeName, Object attributeValue) {

		if (attributeValue == null) {
			removeAttribute(coverDot(attributeName));
		} else {
			this.attrs.put(coverDot(attributeName), attributeValue);
		}
	}

	@Override
	public void removeAttribute(String attributeName) {
		this.attrs.remove(coverDot(attributeName));
	}

	@Override
	public Instant getCreationTime() {
		return Instant.ofEpochMilli(this.createdMillis);
	}

	public void setCreationTime(long created) {
		this.createdMillis = created;
	}

	@Override
	public Instant getLastAccessedTime() {
		return Instant.ofEpochMilli(this.accessedMillis);
	}

	@Override
	public void setLastAccessedTime(Instant lastAccessedTime) {

		this.accessedMillis = lastAccessedTime.toEpochMilli();
		this.expireAt = Date.from(lastAccessedTime.plus(Duration.ofSeconds(this.intervalSeconds)));
	}

	@Override
	public Duration getMaxInactiveInterval() {
		return Duration.ofSeconds(this.intervalSeconds);
	}

	@Override
	public void setMaxInactiveInterval(Duration interval) {
		this.intervalSeconds = interval.getSeconds();
	}

	@Override
	public boolean isExpired() {
		return this.intervalSeconds >= 0 && new Date().after(this.expireAt);
	}

	@Override
	public boolean equals(Object o) {

		if (this == o) {
			return true;
		}
		if (o == null || getClass() != o.getClass()) {
			return false;
		}
		MongoSession that = (MongoSession) o;
		return Objects.equals(this.id, that.id);
	}

	@Override
	public int hashCode() {
		return Objects.hash(this.id);
	}

	@Override
	public String getId() {
		return this.id;
	}

	public Date getExpireAt() {
		return this.expireAt;
	}

	public void setExpireAt(final Date expireAt) {
		this.expireAt = expireAt;
	}

	boolean hasChangedSessionId() {
		return !getId().equals(this.originalSessionId);
	}

	String getOriginalSessionId() {
		return this.originalSessionId;
	}

}

@@ -20,10 +20,10 @@
 4-20
-16
+22
  the
@@ -676,87 +676,124 @@
 ort 
-org.springframework.lang.Nullable;%0Aimport org.springframework.session.Session;%0A
+java.time.Duration;%0Aimport java.time.Instant;%0Aimport java.util.Date;%0Aimport java.util.HashMap;%0Aimport java.util.Map;
 %0Aimp
@@ -797,37 +797,36 @@
 import java.
+u
 ti
-me.Duration
+l.Objects
 ;%0Aimport jav
@@ -823,35 +823,31 @@
 import java.
+u
 ti
-me.Instan
+l.Se
 t;%0Aimport ja
@@ -854,17 +854,20 @@
 va.util.
-*
+UUID
 ;%0Aimport
@@ -897,16 +897,103 @@
 ctors;%0A%0A
+import org.springframework.lang.Nullable;%0Aimport org.springframework.session.Session;%0A%0A
 /**%0A * S
@@ -1285,16 +1285,20 @@
  unicode
+%0A%09 *
  charact
@@ -1421,16 +1421,20 @@
 aused it
+%0A%09 *
  to get 
@@ -1463,20 +1463,16 @@
 ncoding,
-%0A%09 *
  which i
@@ -1507,16 +1507,20 @@
 s, so we
+%0A%09 *
  migrate
@@ -1590,19 +1590,19 @@
 ring
-%0A%09 *
  binary
+%0A%09 *
  com
@@ -1621,18 +1621,17 @@
 %09 *%0A%09 * 
-@s
+S
 ee https
@@ -3258,17 +3258,19 @@
 e));%0A%09%09%7D
- 
+%0A%09%09
 else %7B%0A%09

Fix formatting