module ExcelReports
  module AudioReports
    module NatGeoMusicCueSheets
      class MainSheet < Worksheet
        def title
          "Nat Geo Music Cue Sheet"
        end

        def fill_content(sheet)
          sheet.add_row ["National Geographic", "", "", "", "", "", "", "", "", ""]
          sheet.add_row ["Music Cue Sheet", "", "", "", "", "", "", "", "", ""]
          sheet.add_row
          sheet.add_row table_headers

          data.each_with_index do |datum, index|
            sheet.add_row [
              index + 1,
              datum.title_and_source_file_name,
              datum.timecode_in,
              datum.timecode_out,
              datum.composers_with_split,
              datum.publishers_with_split,
              datum.catalog,
              datum.origin,
              datum.use,
              datum.duration,
            ]
          end

          sheet.add_row ["", "", "", "", "", "", "", "", "Total Music Duration:", total_duration]
        end

        def format(sheet)
          sheet.column_widths *column_widths
          cells_to_merge.each { |cell| sheet.merge_cells cell }
        end

        def style(sheet)
          sheet.add_style "A1:J1", Styles::BOLD, { sz: 18 }
          sheet.add_style "A2:J2", Styles::BOLD, Styles::FULLY_CENTERED, { sz: 16 }
          sheet.add_style "A#{data_start_index-1}:J#{data_start_index-1}", Styles::BOLD, Styles::THIN_BLACK_BORDER, Styles::WRAP_TEXT

          if data.any?
            sheet.add_style "A#{data_start_index}:J#{data_end_index}", Styles::THIN_BLACK_BORDER
            sheet.add_style "E#{data_start_index}:F#{data_end_index}", Styles::WRAP_TEXT
            sheet.add_style "I#{data_start_index}:I#{data_end_index}", Styles::WRAP_TEXT
          end

          sheet.add_style "I#{data_end_index + 1}", Styles::BOLD, Styles::WRAP_TEXT
        end

        private

        def table_headers
          [
            "No.",
            "Title",
            "In",
            "Out",
            "Composer",
            "Publisher",
            "Record Label / Library",
            "Music Origin",
            "Use",
            "Duration",
          ]
        end

        def column_widths
          [10, 30, 20, 20, 50, 50, 20, 25, 25, 20]
        end

        def cells_to_merge
          %w(A1:J1 A2:J2)
        end

        def data_start_index
          5
        end

        def data_end_index
          (data_start_index + data.size) - 1
        end

        def total_duration
          data.map do |datum| 
            begin
              DurationTimecode.parse(datum.duration)
            rescue ArgumentError
              DurationTimecode.new(0, 0, 0)
            end
          end.sum.to_s
        end
      end
    end
  end
end
