/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package szervletek;

import adat.Adatbázis;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import util.Base64;
import util.StringUtil;

/**
 *
 * @author mufi
 */
public class Ment extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/xml;");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String tartalom = StringUtil.getRequestAsString(request);

            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document dom = builder.parse(new InputSource(new StringReader(tartalom)));
//Azon
            String azon = dom.getDocumentElement().getElementsByTagName("azon").item(0).getTextContent();
//Cím
            String cím = dom.getDocumentElement().getElementsByTagName("cím").item(0).getTextContent();
//Tartalom
            String leírás = dom.getDocumentElement().getElementsByTagName("leírás").item(0).getTextContent();
//Dátum
            String dátumString = dom.getDocumentElement().getElementsByTagName("megjelenés").item(0).getTextContent();
            SimpleDateFormat sdf = new SimpleDateFormat("y-M-D");
            Date dátum = sdf.parse(dátumString);
//Címkék
            List<String> címkék = new ArrayList<String>();
            NodeList nl = dom.getElementsByTagName("címke");
            for (int i = 0; i < nl.getLength(); ++i) {
                címkék.add(nl.item(i).getAttributes().getNamedItem("szöveg").getTextContent());
            }
//szereplők
            List<String> szereplők = new ArrayList<String>();
            NodeList nl1 = dom.getElementsByTagName("szereplő");
            for (int i = 0; i < nl1.getLength(); ++i) {
                szereplők.add(nl1.item(i).getAttributes().getNamedItem("név").getTextContent());
            }
//értékelés
            String értékelés = dom.getDocumentElement().getElementsByTagName("értékelés").item(0).getTextContent();

//korhatáros?
            String korhatáros = "false";
            String korhatár = "0";
            try {
                korhatáros = dom.getDocumentElement().getElementsByTagName("korhatár").item(0).getAttributes().item(0).getTextContent();
                korhatár = dom.getDocumentElement().getElementsByTagName("korhatár").item(0).getTextContent();
            } catch (Exception ex) {
                Element e = dom.createElement("korhatár");
                e.setAttribute("korhatáros", "false");
                dom.getDocumentElement().appendChild(e);
                dom.getDocumentElement().getElementsByTagName("korhatár");
            }

            try {
                int filmazon = Adatbázis.ment(Integer.parseInt(azon), cím, leírás, dátum, szereplők, címkék, Integer.parseInt(értékelés), korhatáros.equals("true") ? true : false, Integer.parseInt(korhatár));

                //kép

                String fájl = dom.getDocumentElement().getElementsByTagName("borítóFájl").item(0).getTextContent();
                if (fájl.length() > 0) {
                    byte[] decodedData = Base64.decode(fájl);
                    File f = new File(getServletContext().getRealPath("") + "/" + filmazon + ".jpg");
                    FileOutputStream fout = new FileOutputStream(f);
                    fout.write(decodedData);
                    fout.close();
                }
                dom.getDocumentElement().getElementsByTagName("azon").item(0).setTextContent(filmazon + "");

            } catch (SQLException ex) {
                Logger.getLogger(Ment.class.getName()).log(Level.SEVERE, null, ex);
            }

            Transformer tr = TransformerFactory.newInstance().newTransformer();
            tr.transform(new DOMSource(dom), new StreamResult(out));

            
        } catch (TransformerException ex) {
            Logger.getLogger(Ment.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseException ex) {
            Logger.getLogger(Ment.class.getName()).log(Level.SEVERE, null, ex);

        } catch (SAXException ex) {
            Logger.getLogger(Ment.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Ment.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
