package ru.erfolk.jforex.utils;

import com.dukascopy.api.system.IClient;

import java.io.InputStream;
import java.util.Properties;

/**
 * Загружает криденшелсы из файла
 */
public class CredentialsLoader {
    private static CredentialsLoader instance;

    private String jnlp;
    private String username;
    private String password;

    private static CredentialsLoader instance() throws Exception {
        if (instance == null) {
            instance = new CredentialsLoader();
        }
        return instance;
    }

    public static boolean connect(IClient client) throws Exception {
        return instance()._connect(client);
    }

    public CredentialsLoader() throws Exception {
        Properties prop = new Properties();
        InputStream is = ClassLoader.getSystemResourceAsStream(".credentials");
        if (is == null) throw new Exception("cann't find file with credentials");
        prop.load(is);
        jnlp = prop.getProperty("jnlp");
        username = prop.getProperty("username");
        password = prop.getProperty("password");
        if (jnlp == null || username == null || password == null) throw new Exception("the credentials are not full");
    }

    private boolean _connect(IClient client) throws java.lang.Exception {
        client.connect(jnlp, username, password);
        //wait for it to connect
        int i = 10; //wait max ten seconds
        while (i > 0 && !client.isConnected()) {
            Thread.sleep(1000);
            i--;
        }
        return client.isConnected();
    }
}
