<commit_before>require 'open-uri'

class League < ActiveRecord::Base
  has_many :seasons

  def index_lifetime_player_matchup_metrics
    unique_players.each { |player| player.index_lifetime_matchup_results }
  end

  def lifetime_player_matchup_metrics
  	body = {
  		query: {
  			filtered: {
  				query: { match_all: {} },
  				filter: {
  					bool: {
  						must: [
  							term: {
  								league_id: self.id
  							}
  						]
  					}
  				}
  			}
  		},
  		size: 1000
  	}

  	response = search.client.search index: :players, body: body

  	docs = response['hits']['hits'].map do |doc|
  		doc['_source']
  	end

  	docs.reject! { |doc| (doc['lifetime_win_percentage'].nil? || doc['lifetime_win_percentage'].nan?) }
  	docs
  end

  def bootstrap_new_season(year)
  	create_season year
  	import_teams year, source_doc("http://games.espn.go.com/flb/standings?leagueId=#{remote_id}&seasonId=#{year}")
  	import_weekly_results year
  end

  private

  def search
    @search ||= Search.new
  end

  def teams(year = nil)
    seasons.map { |season| season.teams }.flatten.uniq
  end

  def unique_players
    teams.map { |team| team.players }.flatten.uniq { |player| player.remote_id }
  end

  def create_season(year)
    Season.create year: year, league: self
  end

  def source_doc(path)
    Nokogiri::HTML open(path)
  end

  def import_teams(year, source)
    season = Season.find_by league: self, year: year

    table = source.css('table.tableBody')
    team_rows = table.css('tr.tableBody')

    team_rows.each do |team_row|
      attributes = team_row.css('a').first.attributes

      unparsed_name = attributes['title'].value
      unparsed_team_link = attributes['href'].value

      parsed_name = unparsed_name.split(' (').first
      parsed_remote_id = unparsed_team_link.match(/teamId=(\d*)/)[1].to_i

      team = Team.find_or_initialize_by season: season, remote_id: parsed_remote_id

      next if team.persisted?

      team.name = parsed_name
      team.save!
    end
  end

  def import_weekly_results(year)
    season = Season.find_by league: self, year: year

    schedule = Nokogiri::HTML open("http://games.espn.go.com/flb/schedule?leagueId=#{remote_id}&seasonId=#{season.year}")

    schedule_table = schedule.css('.tableBody')
    schedule_rows = schedule_table.css('tr')

    matchup_paths = []
<commit_msg>Refactor League<commit_after>require 'open-uri'

class League < ActiveRecord::Base
  has_many :seasons

  def index_lifetime_player_matchup_metrics
    unique_players.each { |player| player.index_lifetime_matchup_results }
  end

  def lifetime_player_matchup_metrics
  	body = {
  		query: {
  			filtered: {
  				query: { match_all: {} },
  				filter: {
  					bool: {
  						must: [
  							term: {
  								league_id: self.id
  							}
  						]
  					}
  				}
  			}
  		},
  		size: 1000
  	}

  	response = search.client.search index: :players, body: body

  	docs = response['hits']['hits'].map do |doc|
  		doc['_source']
  	end

  	docs.reject! { |doc| (doc['lifetime_win_percentage'].nil? || doc['lifetime_win_percentage'].nan?) }
  	docs
  end

  def bootstrap_new_season(year)
  	create_season year
  	import_teams year, source_doc("http://games.espn.go.com/flb/standings?leagueId=#{remote_id}&seasonId=#{year}")
  	import_weekly_results year, source_doc("http://games.espn.go.com/flb/schedule?leagueId=#{remote_id}&seasonId=#{year}")
  end

  private

  def search
    @search ||= Search.new
  end

  def teams(year = nil)
    seasons.map { |season| season.teams }.flatten.uniq
  end

  def unique_players
    teams.map { |team| team.players }.flatten.uniq { |player| player.remote_id }
  end

  def create_season(year)
    Season.create year: year, league: self
  end

  def source_doc(path)
    Nokogiri::HTML open(path)
  end

  def import_teams(year, source)
    season = Season.find_by league: self, year: year

    table = source.css('table.tableBody')
    team_rows = table.css('tr.tableBody')

    team_rows.each do |team_row|
      attributes = team_row.css('a').first.attributes

      unparsed_name = attributes['title'].value
      unparsed_team_link = attributes['href'].value

      parsed_name = unparsed_name.split(' (').first
      parsed_remote_id = unparsed_team_link.match(/teamId=(\d*)/)[1].to_i

      team = Team.find_or_initialize_by season: season, remote_id: parsed_remote_id

      next if team.persisted?

      team.name = parsed_name
      team.save!
    end
  end

  def import_weekly_results(year, source)
    season = Season.find_by league: self, year: year

    schedule_table = source.css('.tableBody')
    schedule_rows = schedule_table.css('tr')

    matchup_paths = []

{'fraction_non_alphanumeric': 0.12176885280922879, 'fraction_numerical': 0.0021362956633198035, 'mean_word_length': 3.0855148342059335, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1028909', 'n_tokens_mistral': 1791, 'n_tokens_neox': 1665, 'n_words': 298}