package org.gumbynet.carnivore.server;

import org.gumbynet.carnivore.utils.Logger;
import org.gumbynet.carnivore.objects.HostLogEntry;

import java.util.Properties;
import java.util.Vector;
import java.util.Date;
import java.sql.*;

/**
 * Carnivore Host Log Handler Thread.

 Copyright (c) 2003, Gumbynet & Damien Gardner Jnr
 All rights reserved.

 Redistribution and use in source and binary forms, with or without modification,
 are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this list
     of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list
     of conditions and the following disclaimer in the documentation and/or other
     materials provided with the distribution.
 * Neither the name of GumbyNet nor the names of its contributors may be used to
     endorse or promote products derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
 OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


 */
public class HostLogHandlerThread extends Thread {

    Properties settings;
    Connection con;
    Vector vcrPendingLogs = new Vector();

    public HostLogHandlerThread (Properties settings, Logger logger) {
        this.settings = settings;
        // Register the DB Driver
        try {
            Class driver = Class.forName(settings.getProperty("dbDriver"));
        } catch (Exception e) {System.out.println("Couldn't register DB Driver!"); }

        try {
            con = DriverManager.getConnection(settings.getProperty("dbServer"), settings.getProperty("dbUser"), settings.getProperty("dbPassword"));
        } catch (Exception e) {
            System.out.println("Can't get DB Connection to "+settings.getProperty("dbDriver"));
            e.printStackTrace();
        }

    }

    public void run() {

        while (true) {
            // Wait for log entries..
            while (vcrPendingLogs.size()==0) {
                try {
                    sleep(5000);
                } catch (InterruptedException e) {
                }
            }

            // We must have an entry, lets process it/them..
            HostLogEntry hleEntry = (HostLogEntry) vcrPendingLogs.remove(0);



            PreparedStatement ps = null;
            ResultSet rs = null;
            try {
                long log_datetime = new Date().getTime();
                ps = con.prepareStatement("insert into host_log (host_id, service_id, log_datetime, log_status, log_title, log_text) values (?, ?, ?, ?, ?, ?)");
                ps.setInt(1, hleEntry.getHostID());
                ps.setInt(2, hleEntry.getServiceID());
                ps.setLong(3, log_datetime);
                ps.setInt(4, hleEntry.getStatusCode());
                ps.setString(5, (hleEntry.getStatusTitle().length()>200?hleEntry.getStatusTitle().substring(0, 200):hleEntry.getStatusTitle()));
                ps.setString(6, (hleEntry.getStatusMessage().length()>2000?hleEntry.getStatusMessage().substring(0, 2000):hleEntry.getStatusMessage()));
                ps.executeUpdate();
                ps.close();

                // Check if this is a change from the previous status for this host/service combo
                ps = con.prepareStatement("select log_newstatus from host_statuschange where host_id=? and service_id=? order by log_datetime desc limit 1 offset 0");
                ps.setInt(1, hleEntry.getHostID());
                ps.setInt(2, hleEntry.getServiceID());
                rs = ps.executeQuery();
                int oldStatus = 0;
                boolean booStatusChange = false;
                if (rs.next()) {
                    if (rs.getInt("log_newstatus")!= hleEntry.getStatusCode())
                        booStatusChange = true;
                        oldStatus = rs.getInt("log_newstatus");
                } else {
                        booStatusChange = true;
                }
                rs.close();
                ps.close();

                if (booStatusChange) {
                    // Need toput in a log entry
                    ps = con.prepareStatement("insert into host_statuschange (host_id, service_id, log_datetime, log_oldstatus, log_newstatus) values (?, ?, ?, ?, ?)");
                    ps.setInt(1, hleEntry.getHostID());
                    ps.setInt(2, hleEntry.getServiceID());
                    ps.setLong(3, log_datetime);
                    ps.setInt(4, oldStatus);
                    ps.setInt(5, hleEntry.getStatusCode());
                    ps.executeUpdate();
                    ps.close();
                }

            } catch (SQLException e) {
                e.printStackTrace();  //To change body of catch statement use Options | File Templates.
                System.out.println(hleEntry.getStatusTitle() + "\n-----\n" +hleEntry.getStatusMessage());
            } finally {
                if (rs!=null) try {rs.close();} catch (Exception e) {}
                if (ps!=null) try {ps.close();} catch (Exception e) {}
            }
//            System.out.println("hleEntry.getHostID() = " + hleEntry.getHostID());
//            System.out.println("hleEntry.getServiceID() = " + hleEntry.getServiceID());
//            System.out.println("hleEntry.getStatusCode() = " + hleEntry.getStatusCode());
//            System.out.println("hleEntry.getStatusTitle() = " + hleEntry.getStatusTitle());
//            System.out.println("hleEntry.getStatusMessage() = " + hleEntry.getStatusMessage());



        }
    }


    public void queueHostLogEntry(HostLogEntry hleEntry) {
        vcrPendingLogs.add(hleEntry);
    }
}
