module ExcelReports
  module GraphicReports
    class DiscoveryGfxCueList
      def initialize(video)
        @video = video
      end

      def to_xls
        DiscoveryGfxCueLists::TextedElementsSheet.build(workbook, graphics_elements_data, graphics_elements_header_data)

        package.to_stream.read
      end

      def filename(format = "xlsx")
        name = [@video.file.filename.to_s, "gfx-cue-list"].map(&:parameterize).join("_")
        [name, format].join(".")
      end

      private

      attr_reader :video

      def graphics_elements_data
        video.graphics_elements.order(timecode_in: :asc).map do |graphics_element|
          GraphicsElementsData.new(
            graphics_element.text,
            graphics_element.timecode_in,
            graphics_element.timecode_out,
            graphics_element.duration,
          )
        end
      end

      def graphics_elements_header_data
        GraphicsElementsHeaderData.new(
          video.name,
          video.number,
          video.project.client_name,
          video.project.account.name,
        )
      end

      def workbook
        @workbook ||= package.workbook
      end

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

      class GraphicsElementsData < Struct.new(
        :text,
        :timecode_in,
        :timecode_out,
        :duration,
      )
      end

      class GraphicsElementsHeaderData < Struct.new(
        :program_title,
        :episode,
        :network,
        :company,
      )
      end
    end
  end
end
