package org.slc.sli.api.security.resolve.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.slc.sli.api.security.SLIPrincipal;
import org.slc.sli.api.security.resolve.UserLocator;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.domain.Repository;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Attempts to locate a user in SLI mongo data-store
 *
 * @author dkornishev
 */
@Component
public class MongoUserLocator implements UserLocator {

    public static final Logger LOG = LoggerFactory.getLogger(MongoUserLocator.class);

    private static final List<String> ENTITY_NAMES = Arrays.asList("teacher", "staff");

    @Autowired
    private Repository<Entity> repo;

    @Override
    public SLIPrincipal locate(String tenantId, String externalUserId) {
        LOG.info("Locating user {}@{}", externalUserId, tenantId);
        SLIPrincipal user = new SLIPrincipal(externalUserId + "@" + tenantId);
        user.setExternalId(externalUserId);
        
        NeutralQuery neutralQuery = new NeutralQuery();
        neutralQuery.setOffset(0);
        neutralQuery.setLimit(1);
        Map<String, String> paths = new HashMap<String, String>();
        paths.put("metaData.tenantId", tenantId);
        paths.put("body.staffUniqueStateId", externalUserId);
        
        for (String entityName : ENTITY_NAMES) {
            Iterable<Entity> staff = repo.findAllByPaths(entityName, paths, neutralQuery);

            if (staff != null && staff.iterator().hasNext()) {
                Entity entity = staff.iterator().next();
                LOG.info("Matched user: {}@{} -> {}", new Object[] { externalUserId, tenantId, entity.getEntityId() });
                user.setEntity(entity);
                break;
            }
        }
        
        if (user.getEntity() == null) {
            LOG.warn("Failed to locate user {} in the datastore", user.getId());
        }

        return user;
    }

    public void setRepo(Repository repo) {
        this.repo = repo;
    }
}

@@ -83,20 +83,23 @@
 va.util.
-List
+HashMap
 ;%0Aimport
@@ -109,19 +109,20 @@
 va.util.
-Map
+List
 ;%0Aimport
@@ -128,28 +128,24 @@
 t java.util.
-Hash
 Map;%0A%0Aimport
@@ -349,17 +349,16 @@
 sitory;%0A
-%0A
 import o
@@ -1170,32 +1170,68 @@
 xternalUserId);%0A
+        user.setTenantId(tenantId);%0A
         %0A       
@@ -2140,25 +2140,24 @@
 ;%0A        %7D%0A
-%0A
         retu
@@ -2174,83 +2174,7 @@
    %7D
-%0A%0A    public void setRepo(Repository repo) %7B%0A        this.repo = repo;%0A    %7D
 %0A%7D%0A

set the tenant id of the sli principal upon locating in sli