package it.integry.integrywmsnative.gest.login.rest;

import android.util.Log;

import javax.inject.Singleton;

import it.integry.integrywmsnative.core.CommonConst;
import it.integry.integrywmsnative.core.expansion.RunnableArgs;
import it.integry.integrywmsnative.core.rest.RESTBuilder;
import it.integry.integrywmsnative.core.rest.consumers._BaseRESTConsumer;
import it.integry.integrywmsnative.core.rest.model.ServiceRESTResponse;
import it.integry.integrywmsnative.gest.login.dto.LoginAziendaDTO;
import it.integry.integrywmsnative.gest.login.dto.LoginDTO;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

@Singleton
public class LoginRESTConsumer extends _BaseRESTConsumer {


    public void retrieveServerData(String codAzienda, RunnableArgs<LoginAziendaDTO> onComplete, RunnableArgs<Exception> onFailed){

        String host = CommonConst.Login.Azienda.host;
        int port = CommonConst.Login.Azienda.port;

        LoginRESTConsumerService service = RESTBuilder.getService(LoginRESTConsumerService.class, host, port, false, true);
        service.loginAzienda(codAzienda).enqueue(new Callback<>() {
            @Override
            public void onResponse(Call<ServiceRESTResponse<LoginAziendaDTO>> call, Response<ServiceRESTResponse<LoginAziendaDTO>> response) {
                analyzeAnswer(response, "LoginAzienda", onComplete, onFailed);
            }

            @Override
            public void onFailure(Call<ServiceRESTResponse<LoginAziendaDTO>> call, Throwable t) {
                Log.e("LoginAzienda", t.toString());
                onFailed.run(new Exception(t));
            }
        });
    }


    public void authenticate(String host, int port, String username, String password, RunnableArgs<LoginDTO> onComplete, RunnableArgs<Exception> onFailed){
        LoginRESTConsumerService service = RESTBuilder.getService(LoginRESTConsumerService.class, host, port, false);
        service.login(username, password).enqueue(new Callback<>() {

            @Override
            public void onResponse(Call<ServiceRESTResponse<LoginDTO>> call, Response<ServiceRESTResponse<LoginDTO>> response) {
                analyzeAnswer(response, "Login", onComplete, onFailed);
            }

            @Override
            public void onFailure(Call<ServiceRESTResponse<LoginDTO>> call, final Throwable t) {
                Log.e("Login", t.toString());
                onFailed.run(new Exception(t));
            }
        });
    }


}
