package com.virjar.echo.adr.repo;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import com.virjar.echo.adr.R;

import java.util.Objects;
import java.util.UUID;

public class EchoConfig {

    public static final String configFile = "echo_config";
    public static SharedPreferences sharedPreferences;

    private static String defaultServerHost;
    private static int defaultServerPort;

    private static final String defaultApiURL = "http://echo.virjar.com/";
    private static final String loginTokenKey = "loginToken";
    private static final String userNameKey = "userName";
    private static final String userPasswordKey = "password";

    public static void init(Context context) {
        sharedPreferences = context.getSharedPreferences(configFile, Context.MODE_PRIVATE);

        defaultServerHost = context.getString(R.string.default_server_host);
        defaultServerPort = Integer.parseInt(context.getString(R.string.default_server_port));

        getClientId();
        getApiURL();
    }

    public static String getEchoServer() {
        return sharedPreferences.getString("server_host", defaultServerHost);
    }

    public static int getEchoServerPort() {
        return Integer.parseInt(Objects.requireNonNull(sharedPreferences.getString("server_port", String.valueOf(defaultServerPort))));
    }

    public static String getClientId() {
        String echoClientId = sharedPreferences.getString("echo_clientId", "");
        if (TextUtils.isEmpty(echoClientId)) {
            echoClientId = System.currentTimeMillis() + "_" + UUID.randomUUID().toString();
            sharedPreferences.edit().putString("echo_clientId", echoClientId).apply();
        } else {
            return echoClientId;
        }
        return getClientId();
    }

    public static String getApiURL() {
        String serverApiUrl = sharedPreferences.getString("server_api_url", "");
        if (TextUtils.isEmpty(serverApiUrl)) {
            serverApiUrl = defaultApiURL;
            sharedPreferences.edit().putString("server_api_url", serverApiUrl).apply();
        }
        return serverApiUrl;
    }


    public static void updateLoginToken(String token) {
        if (TextUtils.isEmpty(token)) {
            return;
        }
        sharedPreferences.edit().putString(loginTokenKey, token).apply();
    }

    public static String getToken() {
        return sharedPreferences.getString(loginTokenKey, "");
    }


    public static void saveUsernameAndPassword(String userName, String password) {

        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putString(userNameKey, userName);
        edit.putString(userPasswordKey, password);
        edit.apply();
    }

    public static String getUsername() {
        return sharedPreferences.getString(userNameKey, "");
    }

    public static String getPassword() {
        return sharedPreferences.getString(userPasswordKey, "");
    }
}
