/*
    This file is part of the HeavenMS MapleStory Server
    Copyleft (L) 2016 - 2018 RonanLana

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as
    published by the Free Software Foundation version 3 as published by
    the Free Software Foundation. You may not use, modify or distribute
    this program under any other version of the GNU Affero General Public
    License.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package maplereactordropfetcher;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.HashSet;
import java.util.Set;

import java.io.File;

/**
 *
 * @author RonanLana
 
 This application reports in reactor ids that have drops on the SQL table but are
 not yet coded.
 
 */
public class MapleReactorDropFetcher {
    static String host = "jdbc:mysql://localhost:3306/heavenms";
    static String driver = "com.mysql.jdbc.Driver";
    static String username = "root";
    static String password = "";

    static String reactorScriptPath = "../../scripts/reactor";
    
    static String directoryName = "../..";
    static String newFile = "lib/ReactorDropReport.txt";

    static Connection con = null;
    static PrintWriter printWriter = null;
    static InputStreamReader fileReader = null;
    static BufferedReader bufferedReader = null;
    
    static Set<Integer> reactors = new HashSet<>();

    private static void printReportFileHeader() {
        printWriter.println(" # Report File autogenerated from the MapleReactorDropFetcher feature by Ronan Lana.");
        printWriter.println(" # Generated data takes into account several data info from the underlying DB and the server-side files.");
        printWriter.println();
    }
    
    private static int getReactorIdFromFilename(String name) {
        try {
            return Integer.valueOf(name.substring(0, name.indexOf('.')));
        } catch(Exception e) {
            return -1;
        }
    }
    
    private static void removeScriptedReactorids(String directoryName) {
        File directory = new File(directoryName);

        // get all the files from a directory
        File[] fList = directory.listFiles();
        for (File file : fList) {
            if (file.isFile()) {
                reactors.remove(getReactorIdFromFilename(file.getName()));
            }
        }
    }
    
    private static void loadReactoridsOnDB() throws SQLException {
        PreparedStatement ps = con.prepareStatement("SELECT DISTINCT reactorid FROM reactordrops;");
        ResultSet rs = ps.executeQuery();
        
        while(rs.next()) {
            reactors.add(rs.getInt("reactorid"));
        }
        
        rs.close();
        ps.close();
    }
    
    private static List<Integer> getSortedReactorids() {
        List<Integer> sortedReactors = new ArrayList<>(reactors);
        Collections.sort(sortedReactors);
        
        return sortedReactors;
    }
    
    private static void fetchMissingReactorDrops() throws SQLException {
        loadReactoridsOnDB();
        removeScriptedReactorids(reactorScriptPath);
    }
    
    private static void reportMissingReactorDrops() throws SQLException {
        if(!reactors.isEmpty()) {
            printWriter.println("MISSING REACTOR DROP SCRIPTS");
            for(Integer reactorid : getSortedReactorids()) {
                printWriter.println("  " + reactorid);
            }
            printWriter.println("\n");
        }
    }
    
    private static void ReportMissingReactors() {
        try {
            Class.forName(driver).newInstance();
            
            // filter reactorids on DB
            con = DriverManager.getConnection(host, username, password);
            
            System.out.println("Fetching reactors from DB...");
            fetchMissingReactorDrops();
            
            con.close();
            printWriter = new PrintWriter(newFile, "UTF-8");
            
            // report suspects of missing quest drop data, as well as those drop data that may have incorrect questids.
            System.out.println("Reporting results...");
            printReportFileHeader();
            reportMissingReactorDrops();
            
            printWriter.close();
            System.out.println("Done!");
        }

        catch(SQLException e) {
            System.out.println("Warning: Could not establish connection to database to report quest data.");
            System.out.println(e.getMessage());
        }

        catch(ClassNotFoundException e) {
            System.out.println("Error: could not find class");
            System.out.println(e.getMessage());
        }

        catch(InstantiationException e) {
            System.out.println("Error: instantiation failure");
            System.out.println(e.getMessage());
        }

        catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        ReportMissingReactors();
    }
    
}
