/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package DataMapper;

import com.google.common.collect.MapMaker;
import entity.MapBoard;
import entity.MapValues;
import entity.Player;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author install1
 */
public class DataMapperCalls {

    public static Map.Entry<Collection<Player>, Collection<MapBoard>> getAllValues() {
        Collection<Player> allPlayers = new ArrayList();
        ConcurrentMap<String, MapBoard> allMapBoards = new MapMaker().concurrencyLevel(4).makeMap();
        try (Connection con = DBCPDataSource.getConnection()) {
            String sqlQuery_size = "SELECT count(*) FROM `zetimer_table_new`";
            int rows_size = 0;
            try (PreparedStatement ps = con.prepareStatement(sqlQuery_size)) {
                try (ResultSet result = ps.executeQuery()) {
                    result.next();
                    rows_size = result.getInt(1);
                }
            }
            //just a way to fetch 500 results at a time as seemingly struggling with just a select * from table statement.
            String last_steam_auth = "";
            while (allPlayers.size() < rows_size)
            {
                String sqlQuery = "select * from `zetimer_table_new` ztn where ztn.steam_auth > '" + last_steam_auth + "'\n" +
                    "order by steam_auth asc limit 5000 ";
                if (allPlayers.size() == 0)
                {
                    sqlQuery = "select * from `zetimer_table_new` ztn order by steam_auth asc limit 5000";
                }
                //System.out.println("sqlQuery: " + sqlQuery);
                try (PreparedStatement ps = con.prepareStatement(sqlQuery)) {
                    ps.setFetchSize(100);
                    //System.out.println("allplayers size: " + allPlayers.size() + " rows_size: " + rows_size);
                    try (ResultSet result = ps.executeQuery()) {
                        int fetchSize = result.getMetaData().getColumnCount();
                        while (result.next() /*&& limitfetch < 25*/) {
                            int timesCounter = 0;
                            Player player = new Player(result.getString(1), result.getString(2));
                            //System.out.println("player dataMapper: " + player.getName() + "\nsteamid: " + player.getSteamID());
                            int i = 3;
                            while (i <= fetchSize) {
                                Float specificTime = result.getFloat(i);
                                if (specificTime != null && specificTime != 0) {
                                    String columnLabel = result.getMetaData().getColumnLabel(i);
                                    if (!allMapBoards.keySet().contains(columnLabel)) {
                                        allMapBoards.put(columnLabel, new MapBoard(columnLabel));
                                    }
                                    timesCounter++;
                                    MapValues mapValue = new MapValues();
                                    mapValue.setPlayerSteamID(player.getSteamID());
                                    mapValue.setTime(specificTime);
                                    allMapBoards.get(columnLabel).getMapvalues().add(mapValue);
                                }
                                i++;
                            }
                            player.setTimesCount(timesCounter);
                            allPlayers.add(player);
                            last_steam_auth = player.getSteamID();
                        }
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Map.Entry<Collection<Player>, Collection<MapBoard>> entry = new AbstractMap.SimpleEntry(allPlayers, allMapBoards.values());
        return entry;
    }

    public static ConcurrentMap<String, Collection<Integer>> getURLBanners() {
        ConcurrentMap<String, Collection<Integer>> playerRelatedUrlBanners = new MapMaker().concurrencyLevel(4).makeMap();
        String sqlXenforoQuery = "SELECT t2.provider_key, t1.user_group_id FROM `xf_user_group_relation` t1, `xf_user_connected_account` "
                + "t2  WHERE t1.user_id = t2.user_id AND t2.provider = \"steam\"";
        try (Connection con = DBCPDataSource2.getConnection()) {
            try (PreparedStatement ps = con.prepareStatement(sqlXenforoQuery)) {
                try (ResultSet result = ps.executeQuery()) {
                    while (result.next()) {
                        String providerKey = result.getString(1);
                        int groupID = result.getInt(2);
                        String steamID = convertCommunityIdToSteamId(Long.valueOf(providerKey));
                        Collection<Integer> getSteamIDBanners = playerRelatedUrlBanners.getOrDefault(steamID, null);
                        if (getSteamIDBanners == null) {
                            getSteamIDBanners = new ArrayList();
                        }
                        getSteamIDBanners.add(groupID);
                        playerRelatedUrlBanners.put(steamID, getSteamIDBanners);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return playerRelatedUrlBanners;
    }

    private static String convertCommunityIdToSteamId(long communityId) {
        long steamId1 = communityId % 2;
        long steamId2 = communityId - 76561197960265728L;
        steamId2 = (steamId2 - steamId1) / 2;
        return "STEAM_0:" + steamId1 + ":" + steamId2;
    }

    private Map.Entry<String, Integer> GetMapnameAndStage(String mapName) {
        Pattern pattern = Pattern.compile("S(\\d+)");
        Matcher matcher = pattern.matcher(mapName);
        String map = "";
        int stage = 1; //0
        if (matcher.find()) {
            String group = matcher.group();
            map = mapName.substring(0, mapName.indexOf(group));
            stage = Integer.valueOf(group.substring(1));
        } else {
            map = mapName;
        }
        return new AbstractMap.SimpleEntry(map, stage);
    }
}