package org.cru.godtools.domain.authentication;

import com.google.common.base.Optional;
import org.ccci.util.time.Clock;
import org.sql2o.Connection;
import org.jboss.logging.Logger;
import javax.inject.Inject;

/**
 * Created by ryancarlson on 3/26/14.
 */
public class AuthorizationService
{
    Connection sqlConnection;
    Clock clock;

	Logger log = Logger.getLogger(AuthorizationService.class);

    @Inject
    public AuthorizationService(Connection sqlConnection, Clock clock)
    {
        this.sqlConnection = sqlConnection;
        this.clock = clock;
    }

    public Optional<AuthorizationRecord> getAuthorizationRecord(String authTokenParam, String authTokenHeader)
    {
		String authToken = authTokenHeader == null ? authTokenParam : authTokenHeader;

		log.info("Getting authorization for: " + authToken);

		AuthorizationRecord authorizationRecord = sqlConnection.createQuery(AuthenticationQueries.selectByAuthToken)
				.setAutoDeriveColumnNames(true)
				.addParameter("authToken", authToken)
				.executeAndFetchFirst(AuthorizationRecord.class);

		return Optional.fromNullable(authorizationRecord);
	}

	public void recordNewAuthorization(AuthorizationRecord authenticationRecord)
	{
		sqlConnection.createQuery(AuthenticationQueries.insert)
				.addParameter("id", authenticationRecord.getId())
				.addParameter("username", authenticationRecord.getUsername())
				.addParameter("grantedTimestamp", clock.currentDateTime())
				.addParameter("authToken", authenticationRecord.getAuthToken())
                .addParameter("deviceId", authenticationRecord.getDeviceId())
                .addParameter("draftAccess", authenticationRecord.hasDraftAccess())
				.executeUpdate();
	}

    public AccessCodeRecord getAccessCode(String accessCode)
    {
       return sqlConnection.createQuery(AuthenticationQueries.findAccessCode)
                .setAutoDeriveColumnNames(true)
                .addParameter("accessCode", accessCode)
                .executeAndFetchFirst(AccessCodeRecord.class);
    }

    private class AuthenticationQueries
    {
        static final String selectByAuthToken = "SELECT * FROM auth_tokens WHERE auth_token = :authToken";
		static final String insert = "INSERT INTO auth_tokens(id, username, granted_timestamp, auth_token, device_id, draft_access) VALUES(:id, :username, :grantedTimestamp, :authToken, :deviceId, :draftAccess)";
        static final String findAccessCode = "SELECT * FROM access_codes WHERE access_code  = :accessCode";
    }
}

@@ -288,16 +288,25 @@
 rvice%0A%7B%0A
+%09@Inject%0A
     Conn
@@ -327,20 +327,31 @@
 ection;%0A
+%09%0A
     
+@Inject%0A%09
 Clock cl
@@ -421,176 +421,8 @@
 );%0A%0A
-    @Inject%0A    public AuthorizationService(Connection sqlConnection, Clock clock)%0A    %7B%0A        this.sqlConnection = sqlConnection;%0A        this.clock = clock;%0A    %7D%0A%0A
     

remove constructor - Arquillian handles the injection now :)