<commit_before>/**
 * Copyright 2014 Plain Solutions
 *
 * Authors:
 *  <NAME> <<EMAIL>>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.ssutt.core.sql;

import org.ssutt.core.sql.ex.EmptyTableException;
import org.ssutt.core.sql.ex.NoSuchDepartmentException;
import org.ssutt.core.sql.ex.NoSuchGroupException;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;


/**
 * SSUSQLManager is an implementation of TTSQLManager, configured for usage
 * in SSU with H2DB (defined in the constructor)
 *
 * @author <NAME>
 * @since 1.0
 */
public class SSUSQLManager implements TTSQLManager {
    private static Connection conn;
    private static Queries qrs;

    /**
     * Constructor that creates configured TTSQLManager instance for usage in TTDataManager (mainly)
     * @param conn java.sql.Connection of database provider, that should be familiar to instance creator method
     */
    public SSUSQLManager(Connection conn) {
        SSUSQLManager.conn = conn;
    }

    /**
     * Adds departments to the DB.
     * @param departments Map of departments: name-tag. Better to be sorted by displayed name.  
     * @throws SQLException
     */
    @Override
    public void putDepartments(Map<String, String> departments) throws SQLException {
        Statement stmt = conn.createStatement();

        for (String d : new TreeSet<>(departments.keySet())) {
            stmt.executeUpdate(String.format(qrs.qAddDepartment(), d, departments.get(d)));
        }

        stmt.close();
    }

    /**
     * Adds groups to the DB.
     * @param groups list of group names or numbers, that will be displayed to the end-user.
     * @param departmentTag tag of the department to associate with the group in <code>groups</code> table.
     * @throws SQLException
     * @throws NoSuchDepartmentException If no such department found. 
     */
    @Override
    public void putGroups(List<String> groups, String departmentTag) throws SQLException, NoSuchDepartmentException {
        if (departmentExists(departmentTag)) {
            Statement stmt = conn.createStatement();
            Collections.sort(groups);
            for (String g : groups) {
                stmt.executeUpdate(String.format(qrs.qAddGroups(), departmentTag, g));
            }

            stmt.close();
        } else throw new NoSuchDepartmentException();
    }

    /**
     * Adds datetime information about lesson to <code>lessons_datetimes</code> table, if no such datetime found.
     * @param weekID identifier from week_states: even, odd or all.
     * @param sequence the order of the lesson during the day.
     * @param dayID day number in the week, Monday - 1.
     * @return id of the datetime record.
     * @throws SQLException
     */
    @Override
    public int putDateTime(int weekID, int sequence, int dayID) throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(String.format(qrs.qGetDateTimeID(), weekID, sequence, dayID));
        int id = 0;

        while (rs.next()) id = rs.getInt("id");

        if (id == 0) {
            stmt.executeUpdate(String.format(qrs.qAddDateTime(), weekID, sequence, dayID));
            stmt.close();
            id = getLastID("lessons_datetimes");
        }

        return id;
    }

    /**
     * Adds subject to respective table, if not exists.
     * @param info information about subject (displayble, like room, teacher, lesson activity, name).
     * @return id of the added/found subject.
     * @throws SQLException
     */
    @Override
    public int putSubject(String info) throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(String.format(qrs.qGetSubjectID(), info));
        int id = 0;

        while (rs.next()) id = rs.getInt("id");

        if (id == 0) {
            stmt.executeUpdate(String.format(qrs.qAddSubject(), info));
            stmt.close();

            id = getLastID("subjects");
        }


        return id;
    }

    /**
     * Adds the lesson record - which group has this lesson, at what datetime, and, obviously, what is the lesson
     * is on for this group at this particular datetime (week parity, day and time)
     * @param groupID the id of the group (should be taken from <code>groups</code> table.
     * @param dateTimeID the id of datetime (should be taken from <code>lessons_datetimes</code> table.
     * @param subjectID the id of the subject ((should be taken from <code>subjects</code> table.
     * @throws SQLException
     */
    @Override
    public void putLessonRecord(int groupID, int dateTimeID, int subjectID) throws SQLException {
        Statement stmt = conn.createStatement();
        if (!lessonExists(groupID, dateTimeID, subjectID))
            stmt.executeUpdate(String.format(qrs.qAddLessonRecord(), groupID, dateTimeID, subjectID));

        stmt.close();
    }

    /**
     * Gets list of departments, sorted by their printed names with parameters. Since 1.1 we
     * use list of parameters to make department entries more extensionable.
     * @return Map<String, Map</String, String/>> where key is department tag and Map<String, String> all the data with
     * provided names of positions.
     * @throws SQLException
     */
    @Override
    public Map<String, Map<String, String>> getDepartments() throws SQLException {
        Map<String, Map<String, String>> result = new LinkedHashMap<>();

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(qrs.qGetDepartments());

        while (rs.next()) {
            Map<String, String> data = new HashMap<>();
            String tag = rs.getString("tag");
            data.put("name",rs.getString("name"));
            result.put(tag, data);

        }

        stmt.close();
        return result;
    }

    /**
     * Gets only tags from department table from DB.<commit_msg>data in departments is also now packed in LinkedHashMap to preserve order<commit_after>/**
 * Copyright 2014 Plain Solutions
 *
 * Authors:
 *  <NAME> <<EMAIL>>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.ssutt.core.sql;

import org.ssutt.core.sql.ex.EmptyTableException;
import org.ssutt.core.sql.ex.NoSuchDepartmentException;
import org.ssutt.core.sql.ex.NoSuchGroupException;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;


/**
 * SSUSQLManager is an implementation of TTSQLManager, configured for usage
 * in SSU with H2DB (defined in the constructor)
 *
 * @author <NAME>
 * @since 1.0
 */
public class SSUSQLManager implements TTSQLManager {
    private static Connection conn;
    private static Queries qrs;

    /**
     * Constructor that creates configured TTSQLManager instance for usage in TTDataManager (mainly)
     * @param conn java.sql.Connection of database provider, that should be familiar to instance creator method
     */
    public SSUSQLManager(Connection conn) {
        SSUSQLManager.conn = conn;
    }

    /**
     * Adds departments to the DB.
     * @param departments Map of departments: name-tag. Better to be sorted by displayed name.  
     * @throws SQLException
     */
    @Override
    public void putDepartments(Map<String, String> departments) throws SQLException {
        Statement stmt = conn.createStatement();

        for (String d : new TreeSet<>(departments.keySet())) {
            stmt.executeUpdate(String.format(qrs.qAddDepartment(), d, departments.get(d)));
        }

        stmt.close();
    }

    /**
     * Adds groups to the DB.
     * @param groups list of group names or numbers, that will be displayed to the end-user.
     * @param departmentTag tag of the department to associate with the group in <code>groups</code> table.
     * @throws SQLException
     * @throws NoSuchDepartmentException If no such department found. 
     */
    @Override
    public void putGroups(List<String> groups, String departmentTag) throws SQLException, NoSuchDepartmentException {
        if (departmentExists(departmentTag)) {
            Statement stmt = conn.createStatement();
            Collections.sort(groups);
            for (String g : groups) {
                stmt.executeUpdate(String.format(qrs.qAddGroups(), departmentTag, g));
            }

            stmt.close();
        } else throw new NoSuchDepartmentException();
    }

    /**
     * Adds datetime information about lesson to <code>lessons_datetimes</code> table, if no such datetime found.
     * @param weekID identifier from week_states: even, odd or all.
     * @param sequence the order of the lesson during the day.
     * @param dayID day number in the week, Monday - 1.
     * @return id of the datetime record.
     * @throws SQLException
     */
    @Override
    public int putDateTime(int weekID, int sequence, int dayID) throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(String.format(qrs.qGetDateTimeID(), weekID, sequence, dayID));
        int id = 0;

        while (rs.next()) id = rs.getInt("id");

        if (id == 0) {
            stmt.executeUpdate(String.format(qrs.qAddDateTime(), weekID, sequence, dayID));
            stmt.close();
            id = getLastID("lessons_datetimes");
        }

        return id;
    }

    /**
     * Adds subject to respective table, if not exists.
     * @param info information about subject (displayble, like room, teacher, lesson activity, name).
     * @return id of the added/found subject.
     * @throws SQLException
     */
    @Override
    public int putSubject(String info) throws SQLException {
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(String.format(qrs.qGetSubjectID(), info));
        int id = 0;

        while (rs.next()) id = rs.getInt("id");

        if (id == 0) {
            stmt.executeUpdate(String.format(qrs.qAddSubject(), info));
            stmt.close();

            id = getLastID("subjects");
        }


        return id;
    }

    /**
     * Adds the lesson record - which group has this lesson, at what datetime, and, obviously, what is the lesson
     * is on for this group at this particular datetime (week parity, day and time)
     * @param groupID the id of the group (should be taken from <code>groups</code> table.
     * @param dateTimeID the id of datetime (should be taken from <code>lessons_datetimes</code> table.
     * @param subjectID the id of the subject ((should be taken from <code>subjects</code> table.
     * @throws SQLException
     */
    @Override
    public void putLessonRecord(int groupID, int dateTimeID, int subjectID) throws SQLException {
        Statement stmt = conn.createStatement();
        if (!lessonExists(groupID, dateTimeID, subjectID))
            stmt.executeUpdate(String.format(qrs.qAddLessonRecord(), groupID, dateTimeID, subjectID));

        stmt.close();
    }

    /**
     * Gets list of departments, sorted by their printed names with parameters. Since 1.1 we
     * use list of parameters to make department entries more extensionable.
     * @return Map<String, Map</String, String/>> where key is department tag and Map<String, String> all the data with
     * provided names of positions.
     * @throws SQLException
     */
    @Override
    public Map<String, Map<String, String>> getDepartments() throws SQLException {
        Map<String, Map<String, String>> result = new LinkedHashMap<>();

        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery(qrs.qGetDepartments());

        while (rs.next()) {
            Map<String, String> data = new LinkedHashMap<>();
            String tag = rs.getString("tag");
            data.put("name",rs.getString("name"));
            result.put(tag, data);

        }

        stmt.close();
        return result;
    }

    /**
     * Gets only tags from department table from DB.
{'fraction_non_alphanumeric': 0.09940266503293001, 'fraction_numerical': 0.0027569306172461326, 'mean_word_length': 2.7918118466898956, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 57, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5779022', 'n_tokens_mistral': 3597, 'n_tokens_neox': 3472, 'n_words': 1232}