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

package elektra;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.BufferedOutputStream;
import java.io.FileWriter;
import java.util.ResourceBundle;
import java.util.Properties;
import java.util.Date;
import java.net.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletContext;
import javax.servlet.ServletConfig;
import javax.servlet.http.HttpSession;
import javax.servlet.RequestDispatcher;

import javax.mail.*;
import javax.activation.*;
import javax.mail.internet.*;

/**
 *
 * @author Rolfs
 */
public class WebChangeCustomerPassword extends HttpServlet
{

  protected String szElektraConfig = "";
  protected String szElektraServer = "";
  protected String szElektraServerPort = "";

  protected String szRequest = "27";              // Kundenpaßwort ändern
  protected String szVersion = "270";
  protected Integer nDebug;

  protected String strJSP = "";
  protected String strJSPError = "";
  protected String strJSPReload = "";

  protected ServletContext context;
  ResourceBundle resource = ResourceBundle.getBundle("elektra.Resource");

 /** Adresse/Name des Mailservers, definiert in elektra.properties */
  protected String szMailServer = "";
  /** gewuenschte From-Adresse, definiert in elektra.properties */
  protected String szMailFrom = "";
  /** Liste der CC-Adressen, definiert in elektra.properties */
  protected String szMailCC = "";
  /** Liste der BCC-Adressen, definiert in elektra.properties */
  protected String szMailBCC = "";
  /** Liste der Reply-Adressen, definiert in elektra.properties */
  protected String szMailReply = "";
  /** Benutzer auf Mailserver: optional, definiert in elektra.properties */
  protected String szMailUserName = "";
  /** Passwort auf Mailserver: optional, definiert in elektra.properties */
  protected String szMailUserPassword = "";

  
  public void init(ServletConfig config) throws ServletException
  {
    super.init(config);

    // Remember context
    context = config.getServletContext();

    try { szElektraConfig = context.getInitParameter("ElektraConfig"); } catch (Exception e) { e.printStackTrace(); }
    if (null == szElektraConfig)
    {
      throw new ServletException("Servlet configuration property \"ElektraConfig\" is not defined!");
    }

    String szDebug = "";
    try { szDebug = context.getInitParameter("Debug"); } catch (Exception e) { e.printStackTrace(); }
    if (null == szDebug)
      nDebug = new Integer(0);
    else
      nDebug = new Integer(szDebug);

    // Properties laden
    Properties props = new Properties();
    try
    {
      props.load(new FileInputStream(szElektraConfig));

      strJSP = props.getProperty("ChangeCustomerPasswordPage");
      if (null == strJSP)
        strJSP = "/jsp/webchangecustomerpassword.jsp";
      strJSPError = props.getProperty("ChangeCustomerPasswordErrorPage");
      if (null == strJSPError)
        strJSPError = "/jsp/webchangecustomerpassworderr.jsp";
      strJSPReload = props.getProperty("ChangeCustomerPasswordReloadPage");
      if (null == strJSPReload)
        strJSPReload = "/jsp/webchangecustomerpasswordreload.jsp";
    }
    catch (IOException ex)
    {
      ex.printStackTrace();
    }

// Remember context
    context = config.getServletContext();
  }


    /** 
     * 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
    {
    Date d = new Date();  // Getting current date
    ChangeCustomerPasswordInData changecustomerpasswordData = new ChangeCustomerPasswordInData();
    boolean     bHeaderPrinted = false;
    int         nCnt = 1;
    WriteDebug  wd = new WriteDebug();

    String szTemp = "";
    HttpSession session = request.getSession();
    session.getLastAccessedTime();
    //
    try { szTemp = request.getParameter(resource.getString("SysID")); } catch (Exception e) { wd.write(response, "Feld "+resource.getString("SysID")+" fehlt", e, nDebug); }
    changecustomerpasswordData.setSysID(szTemp);
    //
    try { szTemp = request.getParameter(resource.getString("ClientID")); } catch (Exception e) { wd.write(response, "Feld "+resource.getString("ClientID")+" fehlt", e, nDebug); }
    changecustomerpasswordData.setClientID(szTemp);
    //

    try { szTemp = request.getParameter("CustomerNumber"); } catch (Exception e) { wd.write(response, "Feld CustomerNumber fehlt", e, nDebug); }
    if (null == szTemp)
      changecustomerpasswordData.setCustomerNumber("0");
    else
      changecustomerpasswordData.setCustomerNumber(szTemp);

    try { szTemp = request.getParameter("Password"); } catch (Exception e) { wd.write(response, "Feld Password fehlt", e, nDebug); }
    changecustomerpasswordData.setCustomerPassword(szTemp);
    
    try { szTemp = request.getParameter("NewPassword"); } catch (Exception e) { wd.write(response, "Feld NewPassword fehlt", e, nDebug); }
    changecustomerpasswordData.setNewCustomerPassword(szTemp);

    try { szTemp = request.getParameter("EMail"); } catch (Exception e) { wd.write(response, "Feld EMail fehlt", e, nDebug); }
    changecustomerpasswordData.setEMail(szTemp);
      
    changecustomerpasswordData.setSession(session.getId());
    // Properties laden
    Configuration Conf = new Configuration(context, szElektraConfig, "ElektraServerChangeCustomerPassword", changecustomerpasswordData.getSysID(), changecustomerpasswordData.getClientID(), nDebug.intValue());
    szElektraServer = Conf.getServerName();
    szElektraServerPort = Conf.getServerPort();

    szMailServer = Conf.getMailServer();
    szMailFrom = Conf.getMailFrom();
    szMailCC = Conf.getMailCC();
    szMailBCC = Conf.getMailBCC();
    szMailReply = Conf.getMailReply();

    if (null == szElektraServer)
    {
      wd.write(response, "Internal error!<br />System error: Elektra-Server not defined<br />", nDebug);
      context.log("Elektra-Server not defined!");
    }
    else
    {
        // Daten an DB-Server senden
        Socket socket = null;
        ChangeCustomerPasswordOutData changecustomerpasswordOut = new ChangeCustomerPasswordOutData();

        if (nDebug.intValue() > 0)
          context.log("  starting ChangeCustomerpassword.");
        try
        {
          socket = new Socket(szElektraServer, Integer.parseInt(szElektraServerPort));
          if (nDebug.intValue() > 1)
            context.log("  socket created.");

          //BufferedInputStream is = new BufferedInputStream(socket.getInputStream());
          BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
          BufferedOutputStream os = new BufferedOutputStream(socket.getOutputStream());


          // Daten senden
          try { os.write(szVersion.getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          try { os.write(szRequest.getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          // Encryption
          try { os.write("NONE".getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          // compression
          try { os.write("NONE".getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          try { os.write(changecustomerpasswordData.getSysID().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          try { os.write(changecustomerpasswordData.getClientID().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          try { os.write(changecustomerpasswordData.getCustomerNumber().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          try { os.write(changecustomerpasswordData.getCustomerPassword().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          try { os.write(changecustomerpasswordData.getSession().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          try { os.write(changecustomerpasswordData.getNewCustomerPassword().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          try { os.write(changecustomerpasswordData.getEMail().getBytes() ); } catch (IOException e) { e.printStackTrace(); }
          os.write( 9 );
          if (nDebug.intValue() > 1)
            context.log("  flushing: "+os.toString());
          os.flush();

          // Daten senden, nun auf die Buchung warten
          changecustomerpasswordOut.readSock(in, szVersion);
          if (nDebug.intValue() > 4)
          {
            wd.write(response, "<br><h2>Getting:</h2>Error:  "+changecustomerpasswordOut.getErrorCode(), nDebug );
          }
          if (nDebug.intValue() > 0)
            context.log("  changecustomerpasswordData performed.");

          request.setAttribute("changecustomerpasswordData", changecustomerpasswordData);
          request.setAttribute("changecustomerpasswordOut", changecustomerpasswordOut);

          // Im Fehlerfall
          if (0 != changecustomerpasswordOut.getErrorCode())
          {
            context.log("Systemerror: "+changecustomerpasswordOut.getErrorCode());
            //  hole den Request Dispatcher fuer die JSP Datei
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSPError);
            //leite auf die JSP Datei zum Anzeigen der Liste weiter
            dispatcher.forward(request, response);
          }
          else
          {
            //  hole den Request Dispatcher fuer die JSP Datei
            // Alles OK Password per Mail

            if (null != szMailServer)
            {          
               String szMailText = "";
               String szKopfText = "";
               
               szKopfText = szKopfText.concat("Ihr neues Password");
/*               
               szMailText = szMailText.concat("Seher geehrte(r) ");
               szMailText = szMailText.concat(changecustomerpasswordData.getSalution());
               szMailText = szMailText.concat(" ");
               szMailText = szMailText.concat(changecustomerpasswordOut.getName1());
               szMailText = szMailText.concat(" ");
               szMailText = szMailText.concat(changecustomerpasswordOut.getName2());
               szMailText = szMailText.concat(" ");
               szMailText = szMailText.concat(changecustomerpasswordOut.getName3());
               szMailText = szMailText.concat(",\r\n\r\n");
               szMailText = szMailText.concat("anbei das geaenderte Password für Ihren Kundenzugriff auf den Server von Frankfurt Ticket.\r\n\r\n");
               szMailText = szMailText.concat("Ihre Kundennummer :        ");
               szMailText = szMailText.concat(changecustomerpasswordOut.getCustId());
               szMailText = szMailText.concat("\r\n");
               szMailText = szMailText.concat("Ihr geaendertes Password:  ");
               szMailText = szMailText.concat(changecustomerpasswordOut.getNewPassword());
               szMailText = szMailText.concat("\r\n");
                       
               Mail m = new Mail(szMailServer, szMailFrom , changecustomerpasswordOut.getEMail(), szMailBCC, szMailCC, szMailReply, szKopfText, szMailText);
               MailSender.getInstance().sendMail(m);
*/
            }      
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSP);
            //leite auf die JSP Datei zum Anzeigen der Liste weiter
            dispatcher.forward(request, response);
          }
        }
        
        catch (IOException ioex)
        {
          changecustomerpasswordOut.setErrorCode( -999);
          changecustomerpasswordOut.setErrorMessage(ioex.getLocalizedMessage());
          if ( (null != strJSPError) && !strJSPError.equals(""))
          {
            request.setAttribute("changecustomerpasswordData", changecustomerpasswordData);
            request.setAttribute("changecustomerpasswordOut", changecustomerpasswordOut);
            
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(strJSPError);
            //leite auf die JSP Datei zum Anzeigen der Liste weiter
            dispatcher.forward(request, response);
          }
        }
        
        catch (Exception ex)
        {
          ex.printStackTrace();
        }
        finally
        {
          if (socket != null)
          {
            try
            {
              socket.close();
            }
            catch (IOException ioex)
            {
              ioex.printStackTrace();
            }
          }
        }
    }
    } 

    // <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>

}
