<commit_before># Lower-level foosey functions

# database wrapper function that makes it so we don't have to copy code later
# also makes sure the block is performed in a transaction for thread safety
# note that you must use the return keyword at the end of these blocks because
# the transaction block returns its own values
def database
  db = SQLite3::Database.new 'foosey.db'

  yield db
rescue SQLite3::Exception => e
  puts e
  puts e.backtrace
ensure
  db.close if db
end

# dank helper function that returns an array of hashes from execute2 output
def create_query_hash(array)
  names = array.shift
  rval = []
  array.each do |r|
    row = {}
    names.each_with_index { |column, idx| row[column] = r[idx] }
    rval << row
  end
  rval
end

# takes a game_id and returns a string of the game results useful for slack
# if date = true, it will be prepended with a nicely formatted date
def game_to_s(game_id, date, league_id)
  database do |db|
    game = create_query_hash(db.execute2('SELECT
                                            p.DisplayName, g.Score, g.Timestamp
                                          FROM Game g
                                          JOIN Player p
                                          USING (PlayerID)
                                          WHERE g.GameID = :game_id
                                          AND g.LeagueID = :league_id
                                          AND p.LeagueID = :league_id
                                          ORDER BY g.Score DESC',
                                         game_id, league_id))

    s = if date
          Time.at(game.first['Timestamp']).strftime '%b %d, %Y - '
        else
          ''
        end

    game.each do |player|
      s << "#{player['DisplayName']} #{player['Score']} "
    end

    return s.strip
  end
end

def message_slack(text, attach, url)
  data = {
    username: 'Foosey',
    channel: '#foosey',
    text: text,
    attachments: attach,
    icon_url: 'http://foosey.futbol/icon.png'
  }

  uri = URI.parse(url)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.ssl_version = :TLSv1
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  req = Net::HTTP::Post.new(uri.request_uri)
  req.body = data.to_json
  req['Content-Type'] = 'application/json'

  http.request(req)
end

# true if a game with the given id exists, false otherwise
def valid_game?(game_id, league_id)
  database do |db|
    game = db.get_first_value 'SELECT GameID FROM Game
                               WHERE GameID = :game_id
                               AND LeagueID = :league_id',
                              game_id, league_id

    return !game.nil?
  end
end

# true if a player with the given id exists, false otherwise
def valid_player?(player_id, league_id)
  database do |db|
    player = db.get_first_value 'SELECT PlayerID FROM Player
                                 WHERE PlayerID = :player_id
                                 AND LeagueID = :league_id',
                                player_id, league_id

    return !player.nil?
  end
end

# true if league exists
def league_exists?(league_name)
  database do |db|
    league = db.get_first_value 'SELECT * FROM League
                                 WHERE LeagueName = :league_name',
                                league_name

    return !league.nil?
  end
end

# pull and load
# hot hot hot deploys
def update
  app_dir = app_dir
  # there's probably a git gem we could use here
  system "cd #{app_dir} && git pull" unless app_dir.nil?
  system "cd #{File.dirname(__FILE__)} && git pull"
end

def admin?(slack_name, league_id = 1)
  database do |db|
    admin = db.get_first_value 'SELECT Admin from Player
                                WHERE SlackName = :slack_name
                                AND LeagueID = :league_id
                                COLLATE NOCASE',
                               slack_name, league_id
    return admin == 1
  end
end

def app_dir
  database do |db|
    # return dir
    return db.get_first_value 'SELECT Value FROM Config
                               WHERE Setting = "AppDirectory"'
  end
end

# returns array of players and their badges in a given league
def badges(league_id, player_id)
  # get players
  players = player_ids league_id
  badges = Hash.new { |h, k| h[k] = [] }

  # temporary badges go here
  badges[4] << badge('🤵🏼👰🏼', 'Hitched')<commit_msg>Warren requested bad emojis<commit_after># Lower-level foosey functions

# database wrapper function that makes it so we don't have to copy code later
# also makes sure the block is performed in a transaction for thread safety
# note that you must use the return keyword at the end of these blocks because
# the transaction block returns its own values
def database
  db = SQLite3::Database.new 'foosey.db'

  yield db
rescue SQLite3::Exception => e
  puts e
  puts e.backtrace
ensure
  db.close if db
end

# dank helper function that returns an array of hashes from execute2 output
def create_query_hash(array)
  names = array.shift
  rval = []
  array.each do |r|
    row = {}
    names.each_with_index { |column, idx| row[column] = r[idx] }
    rval << row
  end
  rval
end

# takes a game_id and returns a string of the game results useful for slack
# if date = true, it will be prepended with a nicely formatted date
def game_to_s(game_id, date, league_id)
  database do |db|
    game = create_query_hash(db.execute2('SELECT
                                            p.DisplayName, g.Score, g.Timestamp
                                          FROM Game g
                                          JOIN Player p
                                          USING (PlayerID)
                                          WHERE g.GameID = :game_id
                                          AND g.LeagueID = :league_id
                                          AND p.LeagueID = :league_id
                                          ORDER BY g.Score DESC',
                                         game_id, league_id))

    s = if date
          Time.at(game.first['Timestamp']).strftime '%b %d, %Y - '
        else
          ''
        end

    game.each do |player|
      s << "#{player['DisplayName']} #{player['Score']} "
    end

    return s.strip
  end
end

def message_slack(text, attach, url)
  data = {
    username: 'Foosey',
    channel: '#foosey',
    text: text,
    attachments: attach,
    icon_url: 'http://foosey.futbol/icon.png'
  }

  uri = URI.parse(url)

  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.ssl_version = :TLSv1
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  req = Net::HTTP::Post.new(uri.request_uri)
  req.body = data.to_json
  req['Content-Type'] = 'application/json'

  http.request(req)
end

# true if a game with the given id exists, false otherwise
def valid_game?(game_id, league_id)
  database do |db|
    game = db.get_first_value 'SELECT GameID FROM Game
                               WHERE GameID = :game_id
                               AND LeagueID = :league_id',
                              game_id, league_id

    return !game.nil?
  end
end

# true if a player with the given id exists, false otherwise
def valid_player?(player_id, league_id)
  database do |db|
    player = db.get_first_value 'SELECT PlayerID FROM Player
                                 WHERE PlayerID = :player_id
                                 AND LeagueID = :league_id',
                                player_id, league_id

    return !player.nil?
  end
end

# true if league exists
def league_exists?(league_name)
  database do |db|
    league = db.get_first_value 'SELECT * FROM League
                                 WHERE LeagueName = :league_name',
                                league_name

    return !league.nil?
  end
end

# pull and load
# hot hot hot deploys
def update
  app_dir = app_dir
  # there's probably a git gem we could use here
  system "cd #{app_dir} && git pull" unless app_dir.nil?
  system "cd #{File.dirname(__FILE__)} && git pull"
end

def admin?(slack_name, league_id = 1)
  database do |db|
    admin = db.get_first_value 'SELECT Admin from Player
                                WHERE SlackName = :slack_name
                                AND LeagueID = :league_id
                                COLLATE NOCASE',
                               slack_name, league_id
    return admin == 1
  end
end

def app_dir
  database do |db|
    # return dir
    return db.get_first_value 'SELECT Value FROM Config
                               WHERE Setting = "AppDirectory"'
  end
end

# returns array of players and their badges in a given league
def badges(league_id, player_id)
  # get players
  players = player_ids league_id
  badges = Hash.new { |h, k| h[k] = [] }

  # temporary badges go here
  badges[4] << badge('🤵🏼👰🏼', 'Hitched')
  badges[35] << badge('🤒', 'Weak')
  badges[35] << badge('😭', 'Whimpering')
{'fraction_non_alphanumeric': 0.08131176999101528, 'fraction_numerical': 0.0022461814914645105, 'mean_word_length': 1.8056080655324511, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 46, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1031737', 'n_tokens_mistral': 2617, 'n_tokens_neox': 2550, 'n_words': 848}