ActiveAdmin.register_page 'Feed' do
  content do

    # get user information via params
    user_id = nil
    user_id = params[:feed][:user_id] if params[:feed] && params[:feed][:user_id] != ''
    feed_type = 'all'
    feed_type = params[:feed][:feed_type] if params[:feed] && !params[:feed][:feed_type].blank?
    diagnostic_type = 'all'
    diagnostic_type = params[:feed][:diagnostic_type] if params[:feed] && !params[:feed][:diagnostic_type].blank?
    user_name = 'All'
    user_name = User.find(user_id).to_label if user_id

    render :partial => 'form', locals: {user_name: user_name, user_id: user_id }

    page = (params[:page] ||= 1).to_i
    per_page = 100
    offset = (page - 1) * per_page


    # get feed ids
    where_sql = ''
    where_sql = "WHERE user_id = '#{user_id}'" if user_id
    diagnostic_filter_sql = ''
    if diagnostic_type != 'all'
      if where_sql.blank?
        diagnostic_filter_sql = "WHERE type = '#{diagnostic_type}'"
      else
        diagnostic_filter_sql = "AND type = '#{diagnostic_type}'"
      end
    end
    music_session_sql = "SELECT id, 'music_sessions' as type,  created_at FROM music_sessions #{where_sql}"
    recordings_sql = "SELECT DISTINCT recording_id as id, 'recordings' as type, created_at FROM recorded_tracks #{where_sql}"
    diagnostics_sql = "SELECT id, 'diagnostics' as type, created_at FROM diagnostics #{where_sql} #{diagnostic_filter_sql}"

    feeds = []
    if feed_type == 'all'
      feeds << music_session_sql
      feeds << recordings_sql
      feeds << diagnostics_sql
    elsif feed_type == 'recordings'
      feeds << recordings_sql
    elsif feed_type == 'sessions'
      feeds << music_session_sql
    elsif feed_type == 'diagnostics'
      feeds << diagnostics_sql
    else
      raise "Unknown feed_type: #{feed_type}"
    end

    sql_feed_ids = "#{feeds.join(" UNION ALL ")}
                    ORDER BY created_at DESC
                    OFFSET #{offset}
                    LIMIT #{per_page};"

    sql_feed_count = "SELECT COUNT(*) FROM (
                        #{feeds.join(" UNION ALL ")}
                        ORDER BY created_at DESC
                      ) AS IDS;"
    feed_count = ActiveRecord::Base.connection.execute(sql_feed_count).values[0][0].to_i
    id_types = ActiveRecord::Base.connection.execute(sql_feed_ids).values

    @feed_pages = WillPaginate::Collection.create(page, per_page) do |pager|
      pager.total_entries = feed_count
      pager.replace(id_types)
    end

    div class: 'feed-pagination' do
      will_paginate @feed_pages
    end

    recordings = []
    sessions = []
    diagnostics = []
    id_types.each do |id_and_type|
      if id_and_type[1] == "music_sessions"
        sessions << JamRuby::MusicSession.find(id_and_type[0])
      elsif id_and_type[1] == "recordings"
        recordings << JamRuby::Recording.find(id_and_type[0])
      elsif id_and_type[1] == "diagnostics"
        diagnostics << JamRuby::Diagnostic.find(id_and_type[0])
      else
        raise "Unknown type returned from feed ids"
      end
    end

    columns do
      column do
        if sessions.count > 0
          panel "Music Sessions - #{user_name}" do
            table_for(sessions) do
              column :creator do |msh|
                link_to msh.creator.to_label, admin_feed_path({feed: {user_id: msh.creator.id}})
              end
              column :created_at do |msh| msh.created_at.strftime('%b %d %Y, %H:%M') end
              column :duration do |msh| "#{msh.duration_minutes.round(2)} minutes" end
              column :members do |msh|
                uu = msh.unique_users
                if uu.length > 0
                  uu.each do |u|
                    span link_to u.to_label + ', ', admin_feed_path({feed: {user_id: u.id}})
                  end
                else
                  span para 'No members'
                end
              end

              column :band do |msh| auto_link(msh.band, msh.band.try(:name)) end
              column :fan_access do |msh| msh.fan_access end
              column :plays do |msh| msh.plays.count end
              column :likes do |msh| msh.likes.count end
              column :comments do |msh|
                if msh.comment_count > 0
                  text_node "(#{msh.comment_count}) "
                  msh.comments.each do |comment|
                    text_node comment.user.to_label + ', '
                  end
                else
                  span para 'No comments'
                end
              end
            end
          end
        end

        if recordings.count > 0
          panel "Recordings - #{user_name}" do
            table_for(recordings) do
              column :starter do |rec|
                link_to rec.owner.to_label, admin_feed_path({feed: {user_id: rec.owner.id}})
              end
              column :mixes do |rec|
                ul do
                  mixes = rec.mixes
                  if mixes.count > 0
                    mixes.each do |mix|
                      li do
                        text_node "Created At: #{mix.created_at.strftime('%b %d %Y, %H:%M')}, "
                        text_node "Started At: #{mix.started_at ? mix.started_at.strftime('%b %d %Y, %H:%M') : ''}, "
                        text_node "Completed At: #{mix.completed_at ? mix.completed_at.strftime('%b %d %Y, %H:%M') : ''}, "
                        text_node "Error Count: #{mix.error_count}, "
                        text_node "Error Reason: #{mix.error_reason}, "
                        text_node "Error Detail: #{mix.error_detail}, "
                        text_node "Download Count: #{mix.download_count}, "
                        if !mix.nil? && !mix[:ogg_url].nil?
                          span link_to 'Download OGG', mix.sign_url(3600, 'ogg')
                        else
                          text_node 'OGG download not available'
                        end
                        if !mix.nil? && !mix[:mp3_url].nil?
                          span link_to 'Download MP3', mix.sign_url(3600, 'mp3')
                        else
                          text_node 'MP3 download not available'
                        end
                      end
                    end
                  else
                    span para 'No mixes'
                  end
                end
              end
              column :recorded_tracks do |rec|
                ul do
                  rts = rec.recorded_tracks
                  if rts.count > 0
                    rts.each do |gt|
                      li do
                        span link_to gt.musician.to_label, admin_feed_path({feed: {user_id: gt.musician.id}})
                        span ", #{gt.instrument_id}, "
                        span "Download Count: #{gt.download_count}, "
                        span "Fully uploaded: #{gt.fully_uploaded}, "
                        span "Upload failures: #{gt.upload_failures}, "
                        span "Part failures: #{gt.part_failures}, "
                        if gt[:url]
                          # span link_to 'Download', gt.sign_url(3600)
                        else
                          span 'No track available'
                        end
                      end
                    end
                  else
                    span para 'No recorded tracks'
                  end
                end
              end
              column :claimed_recordings do |rec|
                ul do
                  crs = rec.claimed_recordings
                  if crs.count > 0
                    crs.each do |cr|
                      li do
                        span cr.name
                        span link_to cr.user.to_label, admin_feed_path({feed: {user_id: cr.user.id}})
                        span ", Public: #{cr.is_public}"
                      end
                    end
                  else
                    span para 'No claimed recordings'
                  end
                end
              end
            end
          end
        end

        if diagnostics.count > 0
          panel "Diagnostics - #{user_name}" do
            table_for(diagnostics) do
              column :user do |d|
                span link_to d.user.to_label, admin_feed_path({feed: {user_id: d.user.id}})
              end
              column :created_at do |d| d.created_at.strftime('%b %d %Y, %H:%M') end
              column :type
              column :creator
              column :data do |d|
                span style: "white-space: pre;" do
                  begin
                    JSON.pretty_generate(JSON.parse(d.data))
                  rescue
                    d.data
                  end
                end
              end
            end
          end
        end
      end
    end
    div class: 'feed-pagination' do
      will_paginate @feed_pages
    end
  end
end