# frozen_string_literal: true

require 'fileutils'

# Customize this file, documentation can be found here:
# https://docs.fastlane.tools/actions/
# All available actions:
# can also be listed using the `fastlane actions` command

# Change the syntax highlighting to Ruby
# All lines starting with a # are ignored when running `fastlane`

# If you want to automatically update fastlane if a new version is available:
# update_fastlane

# This is the minimum version number required.
# Update this, if you use features of a newer version
fastlane_version('2.221.1')

STORE_SCREENSHOT_LOCALES = %w[
  en-US ar bg cs-CZ da-DK de-DE el-GR es-ES fi-FI fr-FR hu-HU
  it-IT iw-IL nl-NL pl-PL pt-BR ru-RU sv-SE ta-IN tr-TR uk zh-CN zh-TW
].freeze
EXPECTED_STORE_SCREENSHOTS = (1..8).map { |number| "#{number}.png" }.freeze
SCREENSHOT_CAPTURE_OPTIONS = {
  clear_previous_screenshots: true,
  app_package_name: 'com.futsch1.medtimer.debug',
  tests_package_name: 'com.futsch1.medtimer.debug.test',
  test_instrumentation_runner: 'com.futsch1.medtimer.harness.MedTimerHiltTestRunner',
  reinstall_app: true,
  use_timestamp_suffix: false
}.freeze

def screenshot_apk_paths(project_root)
  app_apk = File.join(project_root, 'app/build/outputs/apk/full/debug/MedTimer-full-debug.apk')
  tests_apk = File.join(project_root,
                        'app/build/outputs/apk/androidTest/full/debug/MedTimer-full-debug-androidTest.apk')
  [app_apk, tests_apk]
end

def capture_android_test_screenshots(context, options)
  context.capture_android_screenshots(**options)
end

def store_screenshot_directories(output_directory)
  STORE_SCREENSHOT_LOCALES.to_h do |locale|
    screenshots_directory = File.join(output_directory, locale, 'images', 'phoneScreenshots')
    screenshots = Dir.glob(File.join(screenshots_directory, '*.png')).map { |path| File.basename(path) }.sort
    unless screenshots == EXPECTED_STORE_SCREENSHOTS
      UI.user_error!(
        "Expected screenshots #{EXPECTED_STORE_SCREENSHOTS}, found #{screenshots} in #{screenshots_directory}"
      )
    end

    [locale, screenshots_directory]
  end
end

def copy_store_screenshots(project_root, screenshots_by_locale)
  screenshots_by_locale.each do |locale, screenshots_directory|
    copy_store_screenshots_for_locale(project_root, locale, screenshots_directory)
  end
end

def copy_store_screenshots_for_locale(project_root, locale, screenshots_directory)
  destination = File.join(project_root, 'fastlane/metadata/android', locale, 'images/phoneScreenshots')
  FileUtils.mkdir_p(destination)
  EXPECTED_STORE_SCREENSHOTS.each do |filename|
    FileUtils.cp(File.join(screenshots_directory, filename), File.join(destination, filename))
  end
  UI.success("Copied #{EXPECTED_STORE_SCREENSHOTS.length} screenshots for #{locale} to #{destination}")
end

def store_screenshot_options(project_root, output_directory)
  app_apk, tests_apk = screenshot_apk_paths(project_root)
  SCREENSHOT_CAPTURE_OPTIONS.merge(
    locales: STORE_SCREENSHOT_LOCALES,
    output_directory: output_directory,
    use_tests_in_classes: ['com.futsch1.medtimer.ScreenshotsTest'],
    app_apk_path: app_apk,
    tests_apk_path: tests_apk
  )
end

def capture_store_screenshots(context)
  project_root = File.expand_path('..', __dir__)
  output_directory = File.join(project_root, 'app/build/store-screenshot-output')
  capture_store_screenshots_for_project(context, project_root, output_directory)
end

def capture_store_screenshots_for_project(context, project_root, output_directory)
  build_screenshot_apks(context)
  options = store_screenshot_options(project_root, output_directory)
  capture_android_test_screenshots(context, options)
  finish_store_screenshot_capture(context, project_root, output_directory)
end

def build_screenshot_apks(context)
  context.gradle(task: 'assembleFullDebug assembleFullDebugAndroidTest')
end

def finish_store_screenshot_capture(context, project_root, output_directory)
  directories = store_screenshot_directories(output_directory)
  copy_store_screenshots(project_root, directories)
  Dir.chdir(project_root) { context.sh('bash', './copyIntroDrawables.sh') }
end

def help_screenshot_options(project_root, output_directory)
  app_apk, tests_apk = screenshot_apk_paths(project_root)
  SCREENSHOT_CAPTURE_OPTIONS.merge(
    locales: ['en-US'],
    output_directory: output_directory,
    use_tests_in_classes: ['com.futsch1.medtimer.HelpScreenshotTest'],
    app_apk_path: app_apk,
    tests_apk_path: tests_apk
  )
end

def capture_help_screenshot(context)
  project_root = File.expand_path('..', __dir__)
  output_directory = File.join(project_root, 'app/build/help-screenshot-output')
  capture_help_screenshot_for_project(context, project_root, output_directory)
end

def capture_help_screenshot_for_project(context, project_root, output_directory)
  build_screenshot_apks(context)
  context.sh('adb', 'shell', 'settings', 'put', 'system', 'time_12_24', '24')
  options = help_screenshot_options(project_root, output_directory)
  capture_android_test_screenshots(context, options)
  copy_help_screenshot(project_root, output_directory)
end

def copy_help_screenshot(project_root, output_directory)
  filename = 'getting-started-upcoming-reminder.png'
  source = File.join(output_directory, 'en-US', 'images', 'phoneScreenshots', filename)
  ensure_screenshot_exists(source)
  destination = File.join(project_root, 'docs/help/images', filename)
  FileUtils.cp(source, destination)
  UI.success("Copied AndroidTest screenshot to #{destination}")
end

def ensure_screenshot_exists(source)
  UI.user_error!("Expected focused guide screenshot at #{source}") unless File.file?(source)
end

platform(:android) do
  desc('Build debug and test APK for screenshots')
  lane(:build_and_screengrab) do
    gradle(task: 'assembleDebug assembleAndroidTest')
    capture_android_screenshots
  end

  desc('Capture Play Store screenshots for every supported locale and update the store and intro assets')
  lane(:capture_store_screenshots) { capture_store_screenshots(self) }

  desc('Capture the beginner guide image with its focused AndroidTest and copy it into the guide assets')
  lane(:capture_help_screenshot) { capture_help_screenshot(self) }
end
