//$Id: DovolenaAction.java,v 1.5 2007/11/30 15:30:21 xvymv01 Exp $
package cz.triangle.dostal.prace.action;

import java.text.DateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.hibernate.Hibernate;
import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.Transaction;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import struts.HibernatePlugIn;
import cz.triangle.dostal.prace.Dovolena;
import cz.triangle.dostal.prace.form.DovolenaForm;
import cz.triangle.dostal.prace.form.VyberUzivatelForm;
import cz.triangle.dostal.trzby.Uzivatel;
import cz.triangle.util.Kalendar;

public class DovolenaAction extends DispatchAction {

	public static String SUCCESS = "vypis";
	public static String CHYBA = "chyba";
	public static String AKCE = "akce";
	public static String AKCE_PO_ODESLANI = "akce_po_odeslani";
	public int ID_TYP = 1;
	public String ODKAZ_TYP = "dovolena";

	public ActionForward execute(
		ActionMapping mapping,
		ActionForm form,
		HttpServletRequest request,
		HttpServletResponse response)
		throws Exception {

		ActionForward forward = null;

		forward = super.execute(mapping, form, request, response);

		vypis(mapping, form, request, response);

		return forward;

	}

	public ActionForward novy(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

		request.setAttribute(AKCE_PO_ODESLANI, "zapsatnovy");

		return mapping.findForward(SUCCESS);
	}

	public ActionForward smazat(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

		HttpSession httpSession = request.getSession();
		if (httpSession.isNew()){
			request.setAttribute(CHYBA, "Napodařilo se smazat.");
			return mapping.findForward(SUCCESS);
		}
		Session hsess = HibernatePlugIn.sessionFactory(request).openSession();
		Transaction tx = null;
		try {
			tx = hsess.beginTransaction();
			String id_string = request.getParameter("id");
			Dovolena polozka = (Dovolena) hsess.load(Dovolena.class, new Long(id_string));
			hsess.delete(polozka);

			Uzivatel uzivatel = (Uzivatel) httpSession.getAttribute("uzivatel");
			//nasledujici kod se jiz neuziva
			if (ID_TYP==1){
				// prictu dovolenou k zustatku
				Kalendar kal = new Kalendar(new Date());
				int interval = kal.getPocetPracovnichDnu(polozka.getCasOd(),polozka.getCasDo(),true);
				uzivatel.setZustatekDovolena(uzivatel.getZustatekDovolena()+interval);
				hsess.update(uzivatel);
			}
			
			tx.commit();
			request.setAttribute(AKCE_PO_ODESLANI, "zapsat");
			request.setAttribute("id", polozka.getId());
		} catch (HibernateException e) {
			request.setAttribute(CHYBA, "Napodařilo se zapsat změny.");
			if (tx != null)
				tx.rollback();
		} catch (Exception e) {
			request.setAttribute(CHYBA, "Napodařilo se smazat.");
		} finally {
			hsess.close();
		}

		return mapping.findForward(SUCCESS);
	}

	public ActionForward zapsatnovy(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
		throws Exception {

		HttpSession httpSession = request.getSession();
		if (httpSession.isNew()){
			request.setAttribute(CHYBA, "Napodařilo se zapsat změny.");
			return mapping.findForward(SUCCESS);
		}
		Session hsess = HibernatePlugIn.sessionFactory(request).openSession();
		Transaction tx = null;
		try {
			tx = hsess.beginTransaction();
			DovolenaForm polozkaForm = (DovolenaForm) form;
			Dovolena polozka = new Dovolena();

			Uzivatel uzivatel = (Uzivatel) httpSession.getAttribute("uzivatel");

			DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale("cs", "CZ"));
			polozka.setId_uzivatel(uzivatel.getId());
			polozka.setCasOd(dateFormat.parse(polozkaForm.getCasOd()));
			polozka.setCasDo(dateFormat.parse(polozkaForm.getCasDo()));
			polozka.setTyp(ID_TYP);
			// nasledujici kod se jiz nevyuziva
			if (ID_TYP==1){
				// odectu dovolenou od zustatku
				Kalendar kal = new Kalendar(new Date());
				int interval = kal.getPocetPracovnichDnu(polozka.getCasOd(),polozka.getCasDo(),true);
				uzivatel.setZustatekDovolena(uzivatel.getZustatekDovolena()-interval);
				hsess.update(uzivatel);
			} 

			hsess.save(polozka);
			tx.commit();
			request.setAttribute(AKCE_PO_ODESLANI, "zapsat");
		} catch (HibernateException e) {
			request.setAttribute(CHYBA, "Napodařilo se zapsat změny.");
			if (tx != null)
				tx.rollback();
		} catch (Exception e) {
			request.setAttribute(CHYBA, "Napodařilo se zapsat změny.");
		} finally {
			hsess.close();
		}

		return mapping.findForward(SUCCESS);
	}

	public ActionForward zapsat(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

		HttpSession httpSession = request.getSession();
		if (httpSession.isNew()){
			request.setAttribute(CHYBA, "Napodařilo se zapsat změny.");
			return mapping.findForward(SUCCESS);
		}
		Session hsess = HibernatePlugIn.sessionFactory(request).openSession();
		Transaction tx = null;
		try {
			tx = hsess.beginTransaction();
			DovolenaForm polozkaForm = (DovolenaForm) form;
			String id_string = request.getParameter("id");
			Dovolena polozka = (Dovolena) hsess.load(Dovolena.class, new Long(id_string));

			//zjisteni uzivatel
			Uzivatel uzivatel = (Uzivatel) httpSession.getAttribute("uzivatel");

			// nasledujici kod se jiz nepouziva
			if (ID_TYP==1){
				// odectu dovolenou od zustatku
				Kalendar kal = new Kalendar(new Date());
				int interval = kal.getPocetPracovnichDnu(polozka.getCasOd(),polozka.getCasDo(),true);
				uzivatel.setZustatekDovolena(uzivatel.getZustatekDovolena()+interval);
			} 

			DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale("cs", "CZ"));
			polozka.setId_uzivatel(uzivatel.getId());
			polozka.setCasOd(dateFormat.parse(polozkaForm.getCasOd()));
			polozka.setCasDo(dateFormat.parse(polozkaForm.getCasDo()));
			polozka.setTyp(ID_TYP);

			if (ID_TYP==1){
				// prictu dovolenou k zustatku
				Kalendar kal = new Kalendar(new Date());
				int interval = kal.getPocetPracovnichDnu(polozka.getCasOd(),polozka.getCasDo(),true);
				uzivatel.setZustatekDovolena(uzivatel.getZustatekDovolena()-interval); 
				hsess.update(uzivatel);
			}
			
			tx.commit();
			request.setAttribute(AKCE_PO_ODESLANI, "zapsat");
		} catch (HibernateException e) {
			request.setAttribute(CHYBA, "Napodařilo se zapsat změny.");
			if (tx != null)
				tx.rollback();
		} catch (Exception e) {
			request.setAttribute(CHYBA, "Napodařilo se zapsat změny.");
		} finally {
			hsess.close();
		}
		return mapping.findForward(SUCCESS);
	}

	public ActionForward vypis(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		Session hsess = HibernatePlugIn.sessionFactory(request).openSession();
		Transaction tx = null;
		try {
			tx = hsess.beginTransaction();
			HttpSession httpSession = request.getSession();

			DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, new Locale("cs", "CZ"));
			//jestlize je admin nacteni uzivatelu
			String archiv = (String) httpSession.getAttribute("archiv");
			if (request.isUserInRole("admin")){
				List uzivatele = null; 
				if ((archiv!=null) && (archiv.equalsIgnoreCase("ano"))){
					uzivatele = hsess.find("from Uzivatel as uzivatel where uzivatel.konec<? and (uzivatel.skryty<>true or uzivatel.skryty is null) order by uzivatel.prijmeni, uzivatel.jmeno", new Date(), Hibernate.DATE);
				}
				else{
					uzivatele = hsess.find("from Uzivatel as uzivatel where uzivatel.konec>=? and (uzivatel.skryty<>true or uzivatel.skryty is null) order by uzivatel.prijmeni, uzivatel.jmeno", new Date(), Hibernate.DATE);
				}
				request.setAttribute("uzivatele", uzivatele);
				request.setAttribute("admin", new Boolean(true));			
			}
			else{
				request.setAttribute("admin", new Boolean(false));			
			}
			//zjisteni uzivatel
			String uzivJmeno = request.getRemoteUser();
			List uzivateleList = hsess.find("from Uzivatel as uzivatel where uzivatel.uzivJmeno=?", uzivJmeno, Hibernate.STRING);
			Uzivatel uzivatel = (Uzivatel) uzivateleList.get(0);
			//jestlize jsem administrator - uzivatel je vybrany
			if (request.isUserInRole("admin")){
				Uzivatel vybranyUzivatel = (Uzivatel) httpSession.getAttribute("uzivatel");
				if (vybranyUzivatel!=null){
					Iterator iterUzivatel = hsess.iterate("from Uzivatel as uzivatel where uzivatel.uzivJmeno=?", vybranyUzivatel.getUzivJmeno(), Hibernate.STRING);
					uzivatel = (Uzivatel) iterUzivatel.next();
				}
				VyberUzivatelForm uzivForm = new VyberUzivatelForm();
				uzivForm.setId_uzivatel(uzivatel.getId());
				uzivForm.setNavrat(ODKAZ_TYP);
				request.setAttribute("vyberUzivatelForm", uzivForm);
			}
			httpSession.setAttribute("uzivatel", uzivatel);
			// zapisu zustatek dovolene
			// jiz se nepouziva
			if (ID_TYP==1){
				request.setAttribute("zustatekDovolena", new Integer(uzivatel.getZustatekDovolena()));
			}
			List polozky = hsess.find("from Dovolena as dovolena where dovolena.id_uzivatel="+ uzivatel.getId() +" and typ="+String.valueOf(ID_TYP)+" order by casOd");
			request.setAttribute("polozky", polozky);
			
			// nyni vypocitame zustatek dovolene
			Kalendar kal = new Kalendar(new Date());
			int vybranychDnu = 0;
			for (Iterator iter = polozky.iterator(); iter.hasNext();) {
				Dovolena dovolena = (Dovolena) iter.next();
				vybranychDnu += kal.getPocetPracovnichDnu(dovolena.getCasOd(),dovolena.getCasDo(),true);
			}
			request.setAttribute("vybranychDnu", new Integer(vybranychDnu));
			
			String akce = request.getParameter(AKCE);
			DovolenaForm f = new DovolenaForm();
			// po vkladani noveho, opet vkladam novy
			if (((akce != null) && (akce.equalsIgnoreCase("zapsatnovy"))) || ((akce != null) && (akce.equalsIgnoreCase("novy")))) {
				request.setAttribute(AKCE_PO_ODESLANI, "zapsatnovy");
				f.setCasOd(dateFormat.format(new Date()));
				f.setCasDo(dateFormat.format(new Date()));
				request.setAttribute("dovolenaForm", f);
				return mapping.findForward(SUCCESS);
			}

			if (!((akce != null) && (akce.equalsIgnoreCase("novy")))) {
				if (polozky.isEmpty()) {
					//request.setAttribute(AKCE_PO_ODESLANI, "zapsatnovy");
					f.setCasOd(dateFormat.format(new Date()));
					f.setCasDo(dateFormat.format(new Date()));
					request.setAttribute("dovolenaForm", f);
					return mapping.findForward(SUCCESS);
				} else {
					request.setAttribute(AKCE_PO_ODESLANI, "zapsat");
				}
			}

			// zjisteni aktualni vybraneho prvku
			// id predano ze stranky		
			String id_string = request.getParameter("id");
			Long id_long = null;

			// id nebylo predano - mozna byla vlozena nova polozka
			if (((id_string != null) && (id_string.length() == 0)) || (id_string == null)) {
				id_long = (Long) request.getAttribute("id");
			} else {
				// id bylo predano ze stranky - rozparsuju ho
				try {
					id_long = new Long(id_string);
				} catch (NumberFormatException e) {
					request.setAttribute(CHYBA, "Nepodařilo se načíst aktuální položku.");
				}
			}

			// jestlize byla smazana polozka nulluju id
			if ((akce != null) && (akce.equalsIgnoreCase("smazat"))) {
				id_long = null;
			}

			Dovolena aktualniPolozka = null;
			if (id_long != null) {
				try {
					aktualniPolozka = (Dovolena) hsess.load(Dovolena.class, id_long);
				} catch (HibernateException e) {
					request.setAttribute(CHYBA, "Nepodařilo se načíst aktuální položku.");
				}
			}
			// neni zadana zadna polozka - vezmu prvni ze seznamu
			else {
				if ((!polozky.isEmpty()) && (!((akce != null) && (akce.equalsIgnoreCase("novy"))))) {
					request.setAttribute("aktualniPolozka", polozky.get(0));
					aktualniPolozka = (Dovolena) polozky.get(0);
				}
			}
			if (aktualniPolozka != null) {
				BeanUtils.copyProperties(f, aktualniPolozka);
				f.setCasOd(dateFormat.format(aktualniPolozka.getCasOd()));
				f.setCasDo(dateFormat.format(aktualniPolozka.getCasDo()));
				request.setAttribute("dovolenaForm", f);
				request.setAttribute("aktualniPolozka", aktualniPolozka);
			}
			tx.commit();
		} catch (HibernateException e) {
			request.setAttribute(CHYBA, "Napodařilo se načíst položky.");
			if (tx != null)
				tx.rollback();
		} catch (Exception e) {
			request.setAttribute(CHYBA, "Napodařilo se načíst položky.");
		} finally {
			hsess.close();
		}

		return mapping.findForward(SUCCESS);
	}

	public ActionForward unspecified(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
		throws Exception {

		return mapping.findForward(SUCCESS);
	}

}
