# frozen_string_literal: true
class EventController < ApplicationController
  include SessionsHelper
  before_action :logged_in_user
  skip_before_action :verify_authenticity_token, only: :lineup_email

  def show
    team_id = params[:team_id]
    event_id = params[:event_id]
    team = TeamSnap::Team.find(@teamsnap_client, team_id)
    event = TeamSnap::Event.find(@teamsnap_client, event_id)
    availability_summary = TeamSnap::AvailabilitySummary.find(@teamsnap_client, event_id)
    render 'show', locals: { team:, event:, availability_summary: }
  end

  def list
    team_id = params[:team_id]
    team = TeamSnap::Team.find(@teamsnap_client, team_id)
    events = TeamSnap::Event.search(@teamsnap_client, { team_id: })
    availability_summaries = TeamSnap::AvailabilitySummary.search(@teamsnap_client, { team_id: })
    availability_summaries_by_event = {}
    events.each_with_index do |event, _index|
      availability_summary = availability_summaries.find { |a| a.event_id == event.id }
      availability_summaries_by_event[event] = availability_summary
    end
    render 'list',
           locals: { team:, events:, availability_summaries_by_event: }
  end

  def lineup
    team_id = params[:team_id].to_i
    event_id = params[:event_id].to_i
    context = helpers.event_context_with_timeline(team_id, event_id, 4)
    render 'lineup', locals: context
  end
  
  def lineup_params(params)
    params.permit(
        :event_lineup_id,
        :event_lineup_entry_original, 
        event_lineup_entries: [
          :label,
          :sequence,
          :member_id,
          :event_id,
          :id,
          :availability_status_code,
          member: [
            :last_name,
            :first_name,
            :jersey_number,
            :email_addresses
          ]
          
        ]
      
    )
  end
  
  def lineup_email
    params_hash = lineup_params(params).to_h
    p params_hash
    render "lineup_email", locals:params_hash, layout: false
  end
  
  def lineup_submit   
    params_hash = lineup_params(params).to_h
    unless params_hash[:event_lineup_id].blank?
      event_lineup = TeamSnap::EventLineup.find(@teamsnap_client, params_hash[:event_lineup_id])
      event_lineup_id = event_lineup.id
      event_lineup_entries_existing = event_lineup.event_lineup_entries
    else
      event_lineup = TeamSnap::EventLineup.create(@teamsnap_client, {
        :team_id => params[:team_id].to_i,
        :event_id => params[:event_id].to_i
      })
      event_lineup_id = event_lineup.id
      event_lineup_entries_existing = []
    end
    
    params_hash[:event_lineup_entries].each do |lue|
      unless lue[:label] == ""
        if existing_entry = event_lineup_entries_existing.find{|entry| entry.id.to_s == lue[:id]}
          # Exists, update
          # Check if exactly the same and update if not
          unless (
            existing_entry["member_id"].to_s  ==lue[:member_id] and 
            existing_entry["label"]           ==lue[:label]     and 
            existing_entry["sequence"].to_s   ==lue[:sequence]
          )
            TeamSnap::EventLineupEntry.update(@teamsnap_client, lue[:id], 
              {:member_id => lue[:member_id],
                :label => lue[:label],
                :sequence => lue[:sequence]
              }
            )
          end
          
          # remove from list
          event_lineup_entries_existing.delete_at(event_lineup_entries_existing.index(existing_entry))
        else
          lue[:sequence]
          TeamSnap::EventLineupEntry.create(@teamsnap_client, 
            {:member_id => lue[:member_id],
              :label => lue[:label],
              :sequence => lue[:sequence],
              :event_lineup_id => event_lineup_id
            }
          )
        end
      end
    end
    
    event_lineup_entries_existing.each do |lue_existing|
      response = TeamSnap::Api.run(@teamsnap_client, :delete, :event_lineup_entry, lue_existing["id"])
      unless response.status == 204
        raise "Unsuccessful"
      end
    end
    
    render :plain => "Successfully Done!"
  end

  def lineup_card
    team_id = params[:team_id].to_i
    event_id = params[:event_id].to_i
    context = helpers.event_context_with_timeline(team_id, event_id, 4)
    render 'lineup_card', locals: context, layout: false
  end

  def lineup_card_template
    params[:team_id].to_i
    params[:event_id].to_i
    # context = helpers.event_data_with_additional_contexts(team_id, event_id)
    context = {}
    render 'lineup_card_template', locals: { context: }, layout: false
  end
end
