package com.rjconsultores.ventaboletos.rest;

import java.io.InputStream;

import org.apache.http.HttpStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

public class LabelaryService {

	private static final Logger log = LogManager.getLogger(LabelaryService.class);

	private static LabelaryService instance;

	private String URL = "http://api.labelary.com/v1/printers";

	private LabelaryService() {
	}

	public static synchronized LabelaryService getInstance() {
		if (instance == null) {
			instance = new LabelaryService();
		}
		return instance;
	}

	public InputStream retornarImagem(String texto) {

		try {
			Unirest.setTimeouts(0, 0);
			HttpResponse<InputStream> response = Unirest.post(URL + "/8dpmm/labels/4x6/0/>label.png?")
					.header("Content-Type", "application/x-www-form-urlencoded")
					.body(texto)
					.asObject(InputStream.class);

			if (response != null
					&& (response.getStatus() == HttpStatus.SC_OK || response.getStatus() == HttpStatus.SC_CREATED)) {
				return response.getBody();
			} else {
				throw new Exception("erro ao enviar requisicao labelary " + response.getStatusText());
			}
		} catch (Exception e) {
			log.error("erro ao enviar requisicao ", e);
		}
		return null;
	}

}
