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

package com.videokonference.servlets;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
/**
 *
 * @author Pavel
 */
public class GenerateV2XML 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, JDOMException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

        String [] layout={"10","22","33","40","50","60","71","80"};
        String linuxPath = "/home/rv/ivp/applications/v2xml/";

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Videokonference</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Videokonference</h1>");

        int pocetUcastniku = Integer.valueOf(request.getParameter("pocetUcastniku"));


//generování souboru

        File file = new File(linuxPath + "template_videokonf.v2xml");
        if(file.exists()){
            out.println("<p>Výchozí soubor " + file.getName() + " nalezen. Vytvářím výstupní soubor...</p>");
        } else {
            out.println("<p>Výchozí soubor " + file.getName() + " nenalezen!! Kontaktujte prosím administrátora.</p>");
        }

        SAXBuilder builder = new SAXBuilder();
        Document parseFile = builder.build(file);

        Element root = parseFile.getRootElement();
        Element head = root.getChild("head");
        Element state = (root.getChild("body")).getChild("state");
        Element onDtmf = state.getChild("onDtmf");

        List headChildren = head.getChildren();
        List onDtmfChildren = onDtmf.getChildren();
        List stateChildren = state.getChildren();

//vytvoreni elementu ve vystupnim dokumentu pro vsechny ucastniky
        for (int i = 1; i <= pocetUcastniku; i++) {

            Element call = new Element("call").setAttribute(new Attribute("id", ("ucastnik" + i)))
                                              .setAttribute(new Attribute("dialStr", request.getParameter("uc" + i)))
                                              .setAttribute(new Attribute("protocol", "SIP"));

            headChildren.add(call);

            Element start = new Element("start").setAttribute("sourceId", ("ucastnik" + i));
            Element setInView = new Element("setInView").setAttribute("viewId", "vzhled1")
                                                        .setAttribute("region", String.valueOf(i));
            start.addContent(setInView);

            onDtmfChildren.add(start);

            Element onStart = new Element("onStart").setAttribute("sourceId", ("ucastnik" + i));
            Element setSoundLevel = new Element("setSoundLevel").setAttribute("sourceId", ("ucastnik" + i))
                                                                .setAttribute("level", "100");
            Element setVideoChannel = new Element("setVideoChannel").setAttribute("sourceId", ("ucastnik" + i))
                                                                    .setAttribute("direction", "both")
                                                                    .setAttribute("mode", "on");
            onStart.addContent(setSoundLevel);
            onStart.addContent(setVideoChannel);

            stateChildren.add(onStart);
        }

        (onDtmf.getChild("setLayout")).setAttribute("layout", layout[pocetUcastniku]);


        XMLOutputter output = new XMLOutputter();
        output.setFormat(Format.getPrettyFormat());
        OutputStream outFile = new FileOutputStream(linuxPath + "videokonference.v2xml");

        output.output(parseFile, outFile);

        String target = "/result.jsp";
        RequestDispatcher rd;
        rd = request.getRequestDispatcher(target);
        rd.forward(request, response);

        out.println("</body>");
        out.println("</html>");
        

        } 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 {
        try {
            processRequest(request, response);
        } catch (JDOMException ex) {
            Logger.getLogger(GenerateV2XML.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * 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 {
        try {
            processRequest(request, response);
        } catch (JDOMException ex) {
            Logger.getLogger(GenerateV2XML.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

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

}
