package it.integry.integrywmsnative.core.rest;

import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.HashMap;

import it.integry.integrywmsnative.core.exception.NoPrintersFoundException;
import it.integry.integrywmsnative.core.exception.NoResultFromBarcodeException;

/**
 * Created by GiuseppeS on 22/03/2018.
 */

public class CommonRESTException {

    private static String MESSAGE_KEY = "message";
    private static String EXCEPTION_KEY = "exception";

    private static final HashMap<String, HashMap<String, Object>> bindingExceptions = new HashMap<>() {{
        put("Printer not found", new HashMap<>() {{
            put(MESSAGE_KEY, "Stampante non trovata");
            put(EXCEPTION_KEY, NoPrintersFoundException.class);
        }});

        put("barcode non letto correttamente", new HashMap<>() {{
            put(MESSAGE_KEY, "Barcode non letto correttamente");
            put(EXCEPTION_KEY, NoResultFromBarcodeException.class);
        }});
    }};


    public static String tryRecognizeThenGetMessage(Exception ex){

        if(ex instanceof SocketException){
            return "Errore di comunicazione con il server remoto. Riprova.";
        } else if(ex instanceof SocketTimeoutException){
            return "Errore di timeout durante la comunicazione con il server remoto. Riprova.";
        } else {
            return ex.getMessage();
        }

    }


    public static Exception tryRecognizeException(String message) {

        for(String key : bindingExceptions.keySet()) {
            if(message.contains(key)) {
                Class<?> classType = (Class<?>) bindingExceptions.get(key).get(EXCEPTION_KEY);

                try {
                    return (Exception) classType.newInstance();
                } catch (IllegalAccessException | InstantiationException e) {
                    e.printStackTrace();
                }
            }
        }

        return new Exception(message);
    }

}
