module MusicSessionHelper

  def facebook_image_for_music_session(music_session)
    if music_session.band
      path = !music_session.band.large_photo_url.blank? ? music_session.band.large_photo_url : "/assets/web/logo-256.png"
    else
      path = "/assets/web/logo-256.png"
    end

    request.protocol + request.host_with_port + path
  end

  # careful; this mirrors logic of facebook_image_for_music_session
  def facebook_image_size_for_music_session(music_session)
    if music_session.band
      !music_session.band.large_photo_url.blank? ? 200 : 256
    else
      256
    end
  end

  def title_for_music_session(music_session, sharer = nil)
    if music_session.band
      "LIVE SESSION: #{music_session.band.name}"
    else
      unique_users = music_session.unique_users
      if sharer && unique_users.exists?(sharer)
        "LIVE SESSION: #{sharer.name}#{additional_member_count(unique_users, sharer)}"
      else
        "LIVE SESSION: #{music_session.creator.name}#{additional_member_count(unique_users, music_session.creator)}"
      end

    end
  end

  def additional_member_count(unique_users, target_user)
    length = unique_users.length
    if length < 2
      ""
    else
      other_length = length - 1
      if other_length == 1
        other_user_in_array = unique_users - [target_user]
        other_user = other_user_in_array[0]
        " & #{other_user.name}"
      else
        " & #{length - 1} OTHERS"
      end
    end
  end

  def description_for_music_session(music_session)
    truncate(music_session.description, length:250)
  end

  def music_session_languages
    languages = []
    # sort by name
    common_languages = LanguageList::COMMON_LANGUAGES.sort {|a, b| a.name <=> b.name}
    english = LanguageList::LanguageInfo.find('English')
    languages.push(:id => english.iso_639_3, :label => english.name)
    common_languages
    common_languages.reject {|lang| lang == english}.each do |language|
      languages.push(:id => language.iso_639_3, :label => language.name == 'Modern Greek (1453-)' ? 'Greek' : language.name)
    end
    languages
  end

  def scheduled_start_date(music_session)
    music_session.scheduled_start_date
  end

  def pretty_scheduled_start(music_session, with_timezone, shorter = false)
    music_session.pretty_scheduled_start(with_timezone, shorter, current_timezone)
  end

  def pretty_scheduled_start_slot(slot, with_timezone)
    slot.pretty_scheduled_start(with_timezone, current_timezone)
  end

  def timezone_options
    options = ""
    ActiveSupport::TimeZone::MAPPING.each do |display, name|
      tz =  ActiveSupport::TimeZone[name]
      if tz
        options << "<option value='#{display},#{tz.tzinfo.name}' class='label' data-tz='#{tz.tzinfo.name}' data-utc-offset='#{tz.utc_offset}'>#{tz.to_s}</option>"
      end

    end
    options.html_safe
  end

  def timezone_list(options)
    select_tag('timezone-list', timezone_options, options)
  end


end
