/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package com.aliyun.oss.common.auth;

import com.aliyun.oss.common.auth.Credentials;
import com.aliyun.oss.common.utils.AuthUtils;

public class BasicCredentials implements Credentials {

    public BasicCredentials(String accessKeyId, String accessKeySecret, String securityToken) {
        this(accessKeyId, accessKeySecret, securityToken, 0);
    }

    public BasicCredentials(String accessKeyId, String accessKeySecret, String securityToken,
            long expiredDurationSeconds) {
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.securityToken = securityToken;
        this.expiredDurationSeconds = expiredDurationSeconds;
        this.startedTimeInMilliSeconds = System.currentTimeMillis();
    }

    public BasicCredentials withExpiredFactor(double expiredFactor) {
        this.expiredFactor = expiredFactor;
        return this;
    }

    public BasicCredentials withExpiredDuration(long expiredDurationSeconds) {
        this.expiredDurationSeconds = expiredDurationSeconds;
        return this;
    }

    @Override
    public String getAccessKeyId() {
        return accessKeyId;
    }

    @Override
    public String getSecretAccessKey() {
        return accessKeySecret;
    }

    @Override
    public String getSecurityToken() {
        return securityToken;
    }

    @Override
    public boolean useSecurityToken() {
        return this.securityToken != null;
    }

    public boolean willSoonExpire() {
        if (expiredDurationSeconds == 0) {
            return false;
        }
        long now = System.currentTimeMillis();
        return expiredDurationSeconds * expiredFactor < (now - startedTimeInMilliSeconds) / 1000.0;
    }

    protected String accessKeyId;
    protected String accessKeySecret;
    protected String securityToken;

    protected long expiredDurationSeconds;
    protected long startedTimeInMilliSeconds = 0;
    protected double expiredFactor = AuthUtils.DEFAULT_EXPIRED_FACTOR;

}
