package de.ivu.elect.presentation.ui;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.annotation.Nullable;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import net.sf.image4j.codec.ico.ICODecoder;
import net.sf.image4j.codec.ico.ICOEncoder;

@WebServlet("/favicon")
public class FaviconServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.setContentType("image/x-icon");

    setCache(resp);

    Color color = hex2Rgb(req.getQueryString());
    try (InputStream is = getFaviconResourceAsStream()) {
      if (color == null) {
        IOUtils.copy(is, resp.getOutputStream());
      } else {
        List<BufferedImage> images = ICODecoder.read(is);

        for (BufferedImage bufferedImage : images) {
          Graphics2D g2d = bufferedImage.createGraphics();

          g2d.setColor(Color.BLACK);
          g2d.setBackground(Color.BLACK);
          g2d.drawLine(0, bufferedImage.getHeight()-5, bufferedImage.getWidth(), bufferedImage.getHeight()-5);

          g2d.setColor(color);
          g2d.setBackground(color);
          g2d.fillRect(0, bufferedImage.getHeight()-4, bufferedImage.getWidth(), 4);

          g2d.dispose();
        }
        ICOEncoder.write(images, resp.getOutputStream());
      }
    }
  }

  private InputStream getFaviconResourceAsStream() {
    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("app-favicon-custom.ico");
    if (inputStream == null) {
      inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("app-favicon-32x32.ico");
    }
    return inputStream;
  }

  private void setCache(HttpServletResponse resp) {
    try {
      Calendar c = Calendar.getInstance();
      c.setTime(new Date());
      c.add(Calendar.DATE, 100);

      //HTTP header date format: Thu, 01 Dec 1994 16:00:00 GMT
      String o = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz", Locale.US).format(c.getTime());
      resp.setHeader("Expires", o);
      resp.setHeader("Cache-Control", "public, max-age=31536000");
    } catch (Exception e) {
      //ignore
    }
  }

  @Nullable
  public static Color hex2Rgb(String colorStr) {
    if (StringUtils.isBlank(colorStr)) {
      return null;
    }
    try {
      return new Color(
              Integer.valueOf(colorStr.substring(0, 2), 16),
              Integer.valueOf(colorStr.substring(2, 4), 16),
              Integer.valueOf(colorStr.substring(4, 6), 16));
    } catch (Exception e) {
      return null;
    }


  }
}
