/*
 * Copyright Avaya Inc., All Rights Reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF Avaya Inc.
 *
 * The copyright notice above does not evidence any actual or intended
 * publication of such source code.
 *
 * Some third-party source code components may have been modified from their
 * original versions by Avaya Inc.
 *
 * The modifications are Copyright Avaya Inc., All Rights Reserved.
 */
package com.avaya.oceanalytics.openinterface.websocketclient.auth;

import com.avaya.oceanalytics.openinterface.websocketclient.encryption.StringEncryptor;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * Represents user credentials. Transparent encryption/decryption of password could be made using provided
 * {@link StringEncryptor}, otherwise credentials will be stored in plain text.
 * 
 * @author seprokof
 *
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class UserCredentials {

    private StringEncryptor encryptor;

    private String username;
    private String password;

    @Autowired
    public void setEncryptor(StringEncryptor encryptor) {
        this.encryptor = encryptor;
    }

    /*
     * DISCLAIMER: Password logged only for demonstration and debug purposes. Avaya does not recommend you to output any
     * sensitive information such as passwords to log file.
     * 
     */
    @Override
    public String toString() {
        return new ToStringBuilder(this).append("username", username).append("password", password).build();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(1, 3).append(username).append(getPassword()).toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        UserCredentials other = (UserCredentials) obj;
        return new EqualsBuilder().append(username, other.username).append(getPassword(), other.getPassword())
                .isEquals();
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return encryptor != null ? encryptor.decrypt(password) : password;
    }

    public void setPassword(String password) {
        this.password = encryptor != null ? encryptor.encrypt(password) : password;
    }

}
