require "will_paginate/array"

class ReportsController < ApplicationController
  include ProjectContext

  before_action :set_project

  include ProjectLayout

  def index
    @reports = filtered_reports.paginate(page: params[:page])
  end

  private

  def filtered_reports
    results = reports
    
    if params[:query].present?
      results = reports.select{ |report| report.name.include?(params[:query])}
    end

    results
  end

  def reports
    videos = @project.videos.reports_published
    videos.published_at_desc_order.flat_map { |video| build_reports_for(video) }
  end

  def build_reports_for(video)
    client_name = @project.client_name
    reports = case client_name
              when "Nat Geo"
                nat_geo_reports_for(video)
              else
                discovery_reports_for(video)
              end

    reports += default_reports_for(video)
  end

  def default_reports_for(video)
    [
      Report.new(video, "BiG Music Cue Sheet", build_report_path(video, :audio_reports, "big")),
      Report.new(video, "Issues and Concerns Report", build_report_path(video, :issues_and_concerns_reports)),
    ]
  end

  def nat_geo_reports_for(video)
    [
      Report.new(video, "Legal Binder Log", build_report_path(video, :video_reports, "nat_geo")),
      Report.new(video, "Text Graphics Log", build_report_path(video, :graphic_reports, "nat_geo")),
      Report.new(video, "Music Cue Sheet", build_report_path(video, :audio_reports, "nat_geo")),
      Report.new(video, "Original Music Log", build_report_path(video, :audio_reports, "nat_geo-original")),
    ]
  end

  def discovery_reports_for(video)
    [
      Report.new(video, "Production Elements Log", build_report_path(video, :video_reports, "discovery")),
      Report.new(video, "GFX Cue List", build_report_path(video, :graphic_reports, "discovery")),
      Report.new(video, "Music Cue Sheet", build_report_path(video, :audio_reports, "discovery")),
    ]
  end

  def build_report_path(video, category, type = nil)
    # TODO: Use Current for locale
    [video, category, { format: "xlsx", locale: I18n.locale, type: type }]
  end

  class Report
    include ActiveModel::Model

    attr_reader :name, :url

    delegate :number, :name, to: :video, prefix: true

    def initialize(video, name, url)
      @video = video
      @name = name
      @url = url
    end

    def to_partial_path
      "reports/report"
    end

    def published_at
      video.report_published_at
    end

    private

    attr_reader :video
  end
end
