package com.bayer.burp.repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.bayer.burp.domain.Burp;
import com.bayer.burp.domain.Tag;

// see https://spring.io/blog/2015/10/28/react-js-and-spring-data-rest-part-5-security
@Component
@RepositoryEventHandler(Burp.class)
public class SpringDataRestEventHandler {

	private final UserRepository userRepository;
	private final TagRepository tagRepository;
	
	private static final Pattern TAG_PATTERN = Pattern.compile("(?:\\s|\\A|^)[#]+([A-Za-z0-9-_]+)");

	@Autowired
	public SpringDataRestEventHandler(UserRepository userRepository, TagRepository tagRepository) {
		this.userRepository = userRepository;
		this.tagRepository = tagRepository;
	}

	@HandleBeforeCreate
	public void applyUserInformationUsingSecurityContext(Burp burp) {
		
		String username = SecurityContextHolder.getContext().getAuthentication().getName();
		burp.setUser(userRepository.findByName(username));
		
		Matcher matcher = TAG_PATTERN.matcher(burp.getText());
		List<Tag> tags = new ArrayList<Tag>();
		while (matcher.find()) {
			Tag tag = tagRepository.findByName(matcher.group().replace('#', ' ').trim());
			// TODO create tag if doesn't exist
			tags.add(tag) ;
		}
		burp.setTags(tags);
		
		burp.setTimestamp(new Date());
	}
}