module ExcelReports
  module VideoReports
    class NatGeoLegalBinderLog
      attr_reader :video

      def initialize(video)
        @video = video
      end

      def to_xls
        build
        package.to_stream.read
      end

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

      private

      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 data_for(release_type)
        video.
          video_release_confirmations.
          where(releasable_type: release_type).
          order(timecode_in: :asc).
          map { |confirmation| ExcelReports::VideoReports::ReleasableDataAdapter.new(confirmation) }
      end


      def build
        NatGeoLegalBinderLogs::LegalBinderChecklistSheet.build(workbook, [], video)
        NatGeoLegalBinderLogs::AppearanceReleaseLogSheet.build(workbook, appearance_data)
        NatGeoLegalBinderLogs::LocationReleaseLogSheet.build(workbook, location_data)
        NatGeoLegalBinderLogs::AcquiredFootageLogSheet.build(workbook, acquired_media_data)
        NatGeoLegalBinderLogs::ThirdPartyContractLogSheet.build(workbook, [])
        NatGeoLegalBinderLogs::ProductionPersonnelLogSheet.build(workbook, [])
      end

      def workbook
        @workbook ||= package.workbook
      end

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