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.LoginResponseDTO;
import it.integry.integrywmsnative.gest.login.dto.LoginRequestDTO;
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 protocol = CommonConst.Login.Azienda.protocol;
        String host = CommonConst.Login.Azienda.host;
        int port = CommonConst.Login.Azienda.port;

        LoginRESTConsumerService service = RESTBuilder.getService(LoginRESTConsumerService.class, protocol, 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 protocol, String host, int port, String username, String password, RunnableArgs<LoginResponseDTO> onComplete, RunnableArgs<Exception> onFailed) {
        LoginRESTConsumerService service = RESTBuilder.getService(LoginRESTConsumerService.class, protocol, host, port, false);

        LoginRequestDTO loginRequestDTO = new LoginRequestDTO()
                .setUsername(username)
                .setPassword(password);

        service.login(loginRequestDTO).enqueue(new Callback<>() {

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

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


}
