package eu.dnetlib.efg1914.various.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.dnetlib.efg1914.various.locales.MyLocale;
import eu.dnetlib.efg1914.various.utils.SetLocalesVariables;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import eu.dnetlib.efg1914.authoring.components.Item;
import eu.dnetlib.efg1914.authoring.components.Theme;
import eu.dnetlib.efg1914.authoring.components.dao.ItemDAO;
import eu.dnetlib.efg1914.authoring.components.dao.ThemeDAO;

@SuppressWarnings("serial")
public class ChronologyPageServlet extends HttpServlet {

    private ApplicationContext context = null;
    private ItemDAO itemDao = null;
    private ThemeDAO themeDao = null;
    private String sourcePath = null;
    private String locale = null;
    private String locale2 = null;

    private String showLanguages = null;

//	private static Logger logger = Logger.getLogger(ChronologyPageServlet.class);

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        setItemDao((ItemDAO) context.getBean("itemDao"));
        setThemeDao((ThemeDAO) context.getBean("themeDao"));
        setSourcePath((String) context.getBean("gridfsPath"));
        setLocale((String) context.getBean("locale"));
        setLocale2((String) context.getBean("locale2"));

        setShowLanguages((String) context.getBean("showLanguages"));

        if (!(showLanguages.equals("true") || showLanguages.equals("false"))) {
            showLanguages = "false";
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.setProperty("input.encoding", "UTF-8");
        ve.setProperty("output.encoding", "UTF-8");
        String lan = (String) request.getSession().getAttribute("language");
        if (lan == null || lan.isEmpty()) {
            request.getSession().setAttribute("language", locale);
            lan = (String) request.getSession().getAttribute("language");
        }
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();

        VelocityContext context = null;

        Template t = ve.getTemplate("/eu/dnetlib/efg1914/various/servlet/chronology.vm", "UTF-8");
        context = new VelocityContext();

        List<Theme> list = new ArrayList<Theme>();
        for (Theme theme : themeDao.getPublisedThemes()) {
            list.add(theme);
        }
        context.put("themes", list);

        SortedMap<String, List<Item>> yearItemMap = new TreeMap<String, List<Item>>();
        yearItemMap.put("y1", new ArrayList<Item>());
        yearItemMap.put("y2", new ArrayList<Item>());
        yearItemMap.put("y3", new ArrayList<Item>());
        yearItemMap.put("y4", new ArrayList<Item>());
        yearItemMap.put("y5", new ArrayList<Item>());
        yearItemMap.put("y6", new ArrayList<Item>());
        yearItemMap.put("y7", new ArrayList<Item>());
        yearItemMap.put("y8", new ArrayList<Item>());

        int year = -1;
        // Put items in a map according to the production year
        for (Item item : itemDao.getPublishedItems()) {
            if (item.getProductionYear() != null) {
                try {
                    year = Integer.parseInt(item.getProductionYear());

                    if (year < 1914) {
                        yearItemMap.get("y1").add(item);

                    } else if (year > 1918) {
                        yearItemMap.get("y7").add(item);

                    } else {
                        switch (year) {
                            case 1914:
                                yearItemMap.get("y2").add(item);
                                break;

                            case 1915:
                                yearItemMap.get("y3").add(item);
                                break;

                            case 1916:
                                yearItemMap.get("y4").add(item);
                                break;

                            case 1917:
                                yearItemMap.get("y5").add(item);
                                break;

                            case 1918:
                                yearItemMap.get("y6").add(item);
                                break;

                            default:
                                break;
                        }
                    }
                } catch (NumberFormatException nfe) {
                    yearItemMap.get("y8").add(item);
                }

            } else {
                yearItemMap.get("y8").add(item);
            }
        }

			
			/*
            for(String year:itemDao.getItemYears()) {
				String finalyear = null;
				
				if (year.isEmpty() || year.toLowerCase().equals("unknown")){
					finalyear = "Unknown"; 
				} else {
					finalyear = year;
					
				}
				
				
				if (yearItemMap.get(year) == null) {
					yearItemMap.put(finalyear, new ArrayList<Item>());
				}							
				
				for (Item item: itemDao.searchItemsByYear(year)) {					
					yearItemMap.get(finalyear).add(item);
					logger.debug("title: " + item.getTitle());
				}
		
			} */

        context.put("yearItemMap", yearItemMap);
        context.put("gridfsPath", getSourcePath());
        context.put("requestPath", request.getRequestURL().substring(0, request.getRequestURL().length() - request.getServletPath().length()));
        context.put("requestUrl", request.getRequestURL());
        context.put("current", "1");
        LocalizedText localizedText = new LocalizedText();
        localizedText.setLocalizedText(lan);
        context.put("localizedText", localizedText);

        SetLocalesVariables.setContextVariables(context, lan, locale, locale2, showLanguages);
        t.merge(context, writer);

    }

    public String getShowLanguages() {
        return showLanguages;
    }

    public void setShowLanguages(String showLanguages) {
        this.showLanguages = showLanguages;
    }

    public ItemDAO getItemDao() {
        return itemDao;
    }

    public void setItemDao(ItemDAO itemDao) {
        this.itemDao = itemDao;
    }

    public ThemeDAO getThemeDao() {
        return themeDao;
    }

    public void setThemeDao(ThemeDAO themeDao) {
        this.themeDao = themeDao;
    }

    public String getSourcePath() {
        return sourcePath;
    }

    public void setSourcePath(String sourcePath) {
        this.sourcePath = sourcePath;
    }

    public ApplicationContext getContext() {
        return context;
    }

    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    public void setLocale(String locale) {
        this.locale = locale;
    }

    public class LocalizedText {
        private String pageTitle;
        private String title;
        private String pre;
        private String post;
        private String unknown;
        private String year;
        private String country;
        private String provider;
        private String tooltip;
        private String ogTitle;
        private String ogDescription;

        public void setLocalizedText(String lan) {
            try {
                MyLocale myLocale = new MyLocale(lan);
                setPageTitle(myLocale.getValue("chronology.pageTitle"));
                setTitle(myLocale.getValue("chronology.title"));
                setPre(myLocale.getValue("chronology.pre"));
                setPost(myLocale.getValue("chronology.post"));
                setUnknown(myLocale.getValue("chronology.unknown"));
                setYear(myLocale.getValue("chronology.item.year"));
                setCountry(myLocale.getValue("chronology.item.country"));
                setProvider(myLocale.getValue("chronology.item.provider"));
                setTooltip(myLocale.getValue("chronology.item.tooltip"));
                setOgTitle(myLocale.getValue("chronology.og.title"));
                setOgDescription(myLocale.getValue("chronology.og.description"));


            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public String getPageTitle() {
            return pageTitle;
        }

        public void setPageTitle(String pageTitle) {
            this.pageTitle = pageTitle;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getPre() {
            return pre;
        }

        public void setPre(String pre) {
            this.pre = pre;
        }

        public String getPost() {
            return post;
        }

        public void setPost(String post) {
            this.post = post;
        }

        public String getUnknown() {
            return unknown;
        }

        public void setUnknown(String unknown) {
            this.unknown = unknown;
        }

        public String getYear() {
            return year;
        }

        public void setYear(String year) {
            this.year = year;
        }

        public String getCountry() {
            return country;
        }

        public void setCountry(String country) {
            this.country = country;
        }

        public String getProvider() {
            return provider;
        }

        public void setProvider(String provider) {
            this.provider = provider;
        }

        public String getTooltip() {
            return tooltip;
        }

        public void setTooltip(String tooltip) {
            this.tooltip = tooltip;
        }

        public String getOgTitle() {
            return ogTitle;
        }

        public void setOgTitle(String ogTitle) {
            this.ogTitle = ogTitle;
        }

        public String getOgDescription() {
            return ogDescription;
        }

        public void setOgDescription(String ogDescription) {
            this.ogDescription = ogDescription;
        }
    }

    public String getLocale2() {
        return locale2;
    }

    public void setLocale2(String locale2) {
        this.locale2 = locale2;
    }
}
