# frozen_string_literal: true
module PositionLabelFlag
  POSITION_ONLY = 'PO'
  DESIGNATED_RUNNER_FOR = 'DRd'

  # Reverse lookup function
  def self.find_key_by_value(value)
    constants.find { |const| const_get(const) == value.to_s }
  end
end

module PositionCapabilityFlag
  INFIELD = "IF"
  OUTFIELD = "OF"
  CATCHER = "C"
  PITCHER = "P"

  # Reverse lookup function
  def self.find_key_by_value(value)
    constants.find { |const| const_get(const) == value.to_s }
  end
end

module Availability
  YES = 1
  NO = 0
  MAYBE = 2
  UNKNOWN = nil  

  def self.sort_order
    [
      UNKNOWN,
      NO,
      MAYBE,
      YES
    ].reverse
  end
  
  def self.sort_by(a)
    sort_order.index(a.status_code)
  end
  
  # availabilities.sort_by do |a|
  #   [a.status_code || -2, members.find do |m|
  #                           m.id == a.member_id
  #                         end.last_name]
  # end,
  
end

def padleft(a, n, x)
  Array.new([0, n-a.length].max, x)+a
end
def padright(a, n, x)
  a.dup.fill(x, a.length...n)
end

module EventHelper

  def event_context_with_timeline(team_id, event_id, timeline_width)
    current_event = TeamSnap::Event.find(@teamsnap_client, event_id)
    upcoming_events = TeamSnap::Event.search(@teamsnap_client, {
      team_id: team_id, started_after: current_event.start_date, page_size: timeline_width + 1
    })
    future_events = upcoming_events.slice(1,upcoming_events.length)
    past_events = TeamSnap::Event.search(@teamsnap_client, {
      team_id: team_id, started_before: current_event.start_date, page_size: timeline_width, sort_start_date: "desc"
    })
    
    past_events.fill(nil, past_events.length...timeline_width)
    future_events.fill(nil, future_events.length...timeline_width)
    event_timeline = past_events.reverse.concat([current_event]).concat(future_events)
    items = TeamSnap.bulk_load(@teamsnap_client,
                               { :team_id => team_id,
                                 :types => 'team,member,availability_summary,event,event_lineup_entry,opponent,location',
                                 :event__id => event_timeline.reject(&:nil?).map(&:id).join(","),
                                 :scope_to => "event"
                                })

    availabilities = TeamSnap::Availability.search(@teamsnap_client, { event_id: event_timeline.reject(&:nil?).map(&:id).join(',') })
    event_lineups = TeamSnap::EventLineup.search(@teamsnap_client, { event_id: event_timeline.reject(&:nil?).map(&:id).join(',') })
    items.concat(availabilities).concat(event_lineups)
    team = items.find { |item| item.type == 'team' and item.id == team_id }
    members = items.select { |item| item.type == 'member' }

    context = { "team": team, "members": members }

    timeline = {}

    event_timeline.each_with_index do |event, i|
      timepoint = Hash[]
      timepoint[:comparison_to_selected] = i - timeline_width
      if event.nil?
        timepoint[:event].nil?
        %w[availability_summary event_lineup event_lineup_entry opponent location].each do |t|
          timepoint[t.to_sym].nil?
        end
      else
        timepoint[:event] = event
        timepoint[:event_lineup] = event_lineups.find{|l| l.event_id == event.id}
        timepoint[:event_lineup_entry] = items.select{ |item| item.type == "event_lineup_entry" and item.event_lineup_id == timepoint[:event_lineup].id }
        %w[availability_summary].each do |t|
          timepoint[t.to_sym] = items.find { |item| item.type == t and item.event_id == event.id }
        end
        %w[].each do |t|
          timepoint[t.to_sym] = items.select { |item| item.type == t and item.event_id == event.id }
        end
        %w[opponent location].each do |t|
          timepoint[t.to_sym] = items.find { |item| item.type == t and item.id == event["#{t}_id"] }
        end
        timepoint[:by_member] = {}
        members.each do |member|
          timepoint[:by_member][member] = {}
          %w[event_lineup_entry availability].each do |t|
            timepoint[:by_member][member][t.to_sym] = items.find do |item|
              item.type == t and item.event_id == event.id and item.member_id == member.id
            end
          end
        end
        timepoint[:by_member] = Hash[timepoint[:by_member].sort_by{|member, d| [ Availability::sort_by(d[:availability]), member.last_name]}]
      end
      timeline[event] = timepoint

    end
    context[:timeline] = timeline.map { |k, v| v }
    context[:timeline][timeline_width].each { |k, v| context[k] = v }
    context
  end
  
  def extract_flags(event_lineup_entry)
    if matches = event_lineup_entry[:label].match(/(?<label>[A-z0-9]+)\s*\[(?<flags>[A-z,\s]+)\]/)
      label = matches[:label]
      flags = matches[:flags].split(",").map{|f| f.strip}
      return [label, flags]
    else
      return [event_lineup_entry[:label], []]
    end
  end
  
  def join_flags(event_lineup_entry, flags)
    unless !event_lineup_entry
    s = event_lineup_entry.label
     if flags and flags.length > 0
      s = "#{s} [#{flags.join(', ')}]"
    end
    else
      ""
    end
  end 
  
end
