package com.vcint.content;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vcint.commons.sql.SQLUtil;
import com.vcint.commons.sql.ResinConnectionManager;

/**
 * <p>
 * updateMessages
 * </p>
 * <p>
 * Description: takes the form from messageEditor.java, reads all the message data and writes it to the DB
 * </p>
 * <p>
 * Copyright: Copyright (c) 2003
 * </p>
 * <p>
 * Company: LVS
 * </p>
 * @author Simon Hobbs
 * @version 1.0
 */

public class messageUpdate extends HttpServlet {

    // These will be set from the request object.
    private java.util.Hashtable _siteMessages = new Hashtable(30);

    // private static final String CONTENT_TYPE = "text/html";

    // Initialize global variables
    public void init() throws ServletException {
    }

    // Process the HTTP Post request
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF8");
        System.out.println("Coming inside of service method. ");
        System.out.println("Service method. charcter encoding "+request.getCharacterEncoding());
        
        PrintWriter out = response.getWriter();
        if (null == request.getParameter("submitted")) {
            out.println("\n<!-- messageUpdate.java: No submit required -->\n");
            return;
        }
        out.println(loadParameters(request));
        out.println(updateDB());

    }

    // Clean up resources
    public void destroy() {
    }

    private String updateDB() {
        StringBuffer html = new StringBuffer();
        Enumeration rows = null;
        PreparedStatement pstmt = null;
        int rowsUpdated = 0;
        ResinConnectionManager cm = null;
        Connection con = null;

        if (_siteMessages == null) {
            return "No changes made";
        }

        rows = _siteMessages.elements();

        try {

            cm = new ResinConnectionManager();
            con = cm.getConnection();

            pstmt = con.prepareStatement("UPDATE HOMEPAGETEASERS SET " + "CONTENT = ? , " + "ENABLEDYN = ? " + "WHERE ID = ? ");

            while (rows.hasMoreElements()) {
                MessageRow mr = (MessageRow) rows.nextElement();
                if ((mr.ID <= 0) || (mr.message == null) || (mr.enabledYN == -1)) {
                    html.append("Error: invalid params: " + mr.ID + "," + mr.enabledYN);
                } else {
                    // else params are good...
                    pstmt.setString(1, mr.message);
                    pstmt.setInt(2, mr.enabledYN);
                    pstmt.setLong(3, mr.ID);
                    rowsUpdated += pstmt.executeUpdate();
                } // else params are good...
            } // while more rows

            if (rowsUpdated > 0) {
                html.append("Success: " + rowsUpdated + " rows updated");
            }

            con.commit();

            return html.toString();

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("error happened!");
            return "ERROR in messageUpdate.java, " + e.toString();
        } finally { // catch
            SQLUtil.cleanup(pstmt);
            SQLUtil.cleanup(con);
        } // finally

    } // updateDB()

    private String loadParameters(HttpServletRequest req) {
        StringBuffer html = new StringBuffer();
        Enumeration paramNames = null;
        MessageRow row = null;
        String name = null; // name is of the format XX.YY where XX = "copy" or "enabledYN" and YY is a teaserID
        String strTeaserID = null;
        int dotPos = -1;
        long iTeaserID = -1;

        paramNames = req.getParameterNames();
        // int paramCount = 0;

        while (paramNames.hasMoreElements()) {

            name = (String) paramNames.nextElement();

            // Logger.logCritical("[com.vcint.content.messageUpdate] " + name + " = " + req.getParameter(name));
            // paramCount++;

            dotPos = name.indexOf(".");

            if (dotPos > 0) {
                strTeaserID = name.substring(dotPos + 1);
                iTeaserID = Integer.parseInt(strTeaserID);

                if ((strTeaserID == null) || (_siteMessages == null)) {
                    return "Error: null parameters";
                }

                if (_siteMessages.containsKey(strTeaserID)) {
                    row = (MessageRow) _siteMessages.get(strTeaserID);
                } else {
                    row = new MessageRow();
                    row.ID = iTeaserID;
                    _siteMessages.put(strTeaserID, row);
                } // if not alread a row

                if (name.startsWith("copy")) {
                    try {
                        row.message = new String(req.getParameter(name).getBytes("utf-8"), "utf-8");
                    } catch (UnsupportedEncodingException ex) {
                        ex.printStackTrace();
                        html.append("<BR>Error in UTF-8 conversion<BR>");
                        row.message = "Error in UTF-8 conversion";
                    } // catch
                } else if (name.startsWith("enabledYN")) { // if was copy
                    if (req.getParameter(name).equals("1")) {
                        row.enabledYN = 1;
                    } else {
                        row.enabledYN = 0;
                    }
                }
                // hidden fields now used instead of the checkboxes
            } // if found a "."
        } // while more params

        // Logger.logCritical("[com.vcint.content.messageUpdate] paramCount = " + paramCount);

        return html.toString();

    } // loadParameters()
}
