module ExcelReports
  module VideoReports
    class DiscoveryProductionElementsLog
      attr_reader :video

      def initialize(video)
        @video = video
      end

      def to_xls
        build
        package.to_stream.read
      end

      def filename(format = "xlsx")
        name = [video.file.filename.to_s, "production-elements-log"].map(&:parameterize).join("_")
        [name, format].join(".")
      end

      private

      def talent_data
        @talent_data ||= data_for("TalentRelease")
      end

      def appearance_data
        @appearance_data ||= data_for("AppearanceRelease")
      end

      def location_data
        @location_data ||= data_for("LocationRelease")
      end

      def acquired_media_data
        @acquired_media_data ||= data_for("AcquiredMediaRelease")
      end

      def music_data
        @music_data ||= data_for("MusicRelease")
      end

      def material_data
        @material_data ||= data_for("MaterialRelease")
      end

      def data_for(release_type)
        video.
          video_release_confirmations.
          where(releasable_type: release_type).
          order(timecode_in: :asc).
          map { |confirmation| ReleasableDataAdapter.new(confirmation) }
      end

      def build
        DiscoveryProductionElementsLogs::MediaRightsCertificationSheet.build(workbook)
        DiscoveryProductionElementsLogs::AcquiredFootageAndStillsSheet.build(workbook, acquired_media_data)
        DiscoveryProductionElementsLogs::MusicSheet.build(workbook, music_data)
        DiscoveryProductionElementsLogs::TalentSheet.build(workbook, talent_data)
        DiscoveryProductionElementsLogs::AppearanceSheet.build(workbook, appearance_data)
        DiscoveryProductionElementsLogs::LocationSheet.build(workbook, location_data)
        DiscoveryProductionElementsLogs::NameProductLogoSheet.build(workbook, material_data)
        DiscoveryProductionElementsLogs::ProductIntegrationSheet.build(workbook)
      end

      def workbook
        @workbook ||= package.workbook
      end

      def package
        @package ||= Axlsx::Package.new
      end
    end
  end
end
