package com.sonian.elasticsearch.http.jetty.security;

import org.eclipse.jetty.http.security.Credential;
import org.eclipse.jetty.security.MappedLoginService;
import org.eclipse.jetty.server.UserIdentity;
import org.eclipse.jetty.util.log.Log;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.get.GetField;
import org.elasticsearch.indices.IndexMissingException;

import java.util.List;

import static org.elasticsearch.common.collect.Lists.newArrayList;

/**
 * @author drewr
 */
public class ESLoginService extends MappedLoginService {
    private volatile String authIndex;

    private volatile String authType;

    private volatile int cacheTime = -1;

    private volatile long lastHashPurge;

    private volatile Client client;

    public ESLoginService() {
    }

    public ESLoginService(String name) {
        setName(name);
    }

    public void setClient(Client client) {
        this.client = client;
    }

    public void setAuthIndex(String authIndex) {
        this.authIndex = authIndex;
    }

    public void setAuthType(String authType) {
        this.authType = authType;
    }

    public void setCacheTime(int cacheTime) {
        this.cacheTime = cacheTime;
    }

    @Override
    protected void doStart() throws Exception {
        super.doStart();
        if (authIndex == null) {
            throw new IllegalArgumentException("User realm " + getName() + " has not been  properly configured - missing authentication index");
        }
        if (authType == null) {
            throw new IllegalArgumentException("User realm " + getName() + " has not been  properly configured - missing authentication type");
        }
        lastHashPurge = 0;
    }

    @Override
    protected void doStop() throws Exception {
        super.doStop();
    }

    @Override
    public UserIdentity login(String username, Object credentials) {
        if (cacheTime >= 0) {
            long now = System.currentTimeMillis();

            if (now - lastHashPurge > cacheTime || cacheTime == 0) {
                _users.clear();
                lastHashPurge = now;
            }
        }

        return super.login(username, credentials);
    }

    @Override
    public UserIdentity loadUser(String user) {
        try {
            GetResponse response = client.prepareGet(authIndex, authType, user)
                    .setFields("password", "roles")
                    .execute().actionGet();
            if (response.exists()) {
                Credential credential = null;
                GetField passwordField = response.field("password");
                if (passwordField != null) {
                    credential = Credential.getCredential((String) passwordField.value());
                }
                String[] roles = getStringValues(response.field("roles"));
                return putUser(user, credential, roles);
            }
        } catch (IndexMissingException e) {
            Log.warn("no auth index [{}]", authIndex);
        } catch (Exception e) {
            Log.warn("error finding user [" + user + "] in [" + authIndex + "]", e);
        }
        return null;
    }

    private String[] getStringValues(GetField field) {
        List<String> values = newArrayList();
        if (field != null) {
            for(Object value : field.values()) {
                if (field.value() instanceof Iterable) {
                    for(Object val : (Iterable) field.value()) {
                        values.add((String) val);
                    }
                } else {
                    values.add((String) value);
                }
            }
        }
        return values.toArray(new String[values.size()]);
    }

    @Override
    public void loadUsers() {
    }
}

@@ -678,24 +678,132 @@
  authType;%0A%0A
+    private volatile String passwordField = %22password%22;%0A%0A    private volatile String rolesField = %22roles%22;%0A%0A
     private 
@@ -1091,32 +1091,94 @@
  client;%0A    %7D%0A%0A
+    public Client getClient() %7B%0A        return client;%0A    %7D%0A%0A
     public void 
@@ -1245,32 +1245,100 @@
 thIndex;%0A    %7D%0A%0A
+    public String getAuthIndex() %7B%0A        return authIndex;%0A    %7D%0A%0A
     public void 
@@ -1401,32 +1401,98 @@
 uthType;%0A    %7D%0A%0A
+    public String getAuthType() %7B%0A        return authType;%0A    %7D%0A%0A
     public void 
@@ -1556,32 +1556,447 @@
 cheTime;%0A    %7D%0A%0A
+    public int getCacheTime() %7B%0A        return cacheTime;%0A    %7D%0A%0A    public void setPasswordField(String passwordField) %7B%0A        this.passwordField = passwordField;%0A    %7D%0A%0A    public String getPasswordField() %7B%0A        return passwordField;%0A    %7D%0A%0A    public void setRolesField(String rolesField) %7B%0A        this.rolesField = rolesField;%0A    %7D%0A%0A    public String getRolesField() %7B%0A        return rolesField;%0A    %7D%0A%0A
     @Override%0A  
@@ -3139,25 +3139,24 @@
 tFields(
-%22
 password
 %22, %22role
@@ -3151,18 +3151,25 @@
 word
-%22
+Field
 , 
-%22
 roles
-%22
+Field
 )%0A  
@@ -3318,32 +3318,35 @@
 etField password
+Get
 Field = response
@@ -3352,25 +3352,24 @@
 e.field(
-%22
 password
 %22);%0A    
@@ -3360,17 +3360,21 @@
 password
-%22
+Field
 );%0A     
@@ -3392,24 +3392,27 @@
 if (password
+Get
 Field != nul
@@ -3487,24 +3487,27 @@
 ng) password
+Get
 Field.value(
@@ -3592,23 +3592,26 @@
 e.field(
-%22
 roles
-%22
+Field
 ));%0A    

Make password and role field name configurable