# This file contains the fastlane.tools configuration
# You can find the documentation at https://docs.fastlane.tools
#
# For a list of all available actions, check out
#
#     https://docs.fastlane.tools/actions
#
# For a list of all available plugins, check out
#
#     https://docs.fastlane.tools/plugins/available-plugins
#

# Uncomment the line if you want fastlane to automatically update itself
# update_fastlane
default_platform(:android)

platform :android do
  s3_url = ENV['S3_URL']
  metadata_dir_name = 'metadata'
  apk_location = '../app/build/outputs/apk/prod/release/'

  desc 'Download keystore from s3'
  private_lane :download_s3_assets do
    # Download the keystore required to sign the app.
    key_file = ENV['KEY_FILE']
    sh "aws --region eu-west-1 s3 cp #{s3_url}#{key_file} ../app"
  end

  desc 'Write Changelog'
  lane :write_changelog do |options|
    version_code = options.fetch(:version_code, 1)
    input_path = options.fetch(:input_path, '../../latest-release-notes.txt')
    output_path =
      options.fetch(:output_path, 'metadata/android/en-GB/changelogs')
    input_full_path = File.expand_path(input_path, File.dirname(__FILE__))
    output = File.read(input_full_path)
    ouput_full_path =
      File.expand_path(
        "#{output_path}/#{version_code}.txt",
        File.dirname(__FILE__),
      )
    default_ouput_full_path =
      File.expand_path("#{output_path}/default.txt", File.dirname(__FILE__))
    File.open(ouput_full_path, 'w') { |f| f.write output }
    File.open(default_ouput_full_path, 'w') { |f| f.write output }
  end

  desc 'Latest Google Play Version Code'
  lane :latest_googleplay_version_code do |options|
    package_name = options[:package_name]
    tracks = options.fetch(:tracks, ['alpha'])
    version_codes =
      tracks.reduce([]) do |final, current_track|
        begin
          track_version_codes =
            google_play_track_version_codes(
              track: current_track,
              package_name: package_name,
              json_key_data: ENV['GOOGLE_PLAY_KEY'],
            )
          final.concat(track_version_codes)
        rescue => gptvcError
          if (
               gptvcError.class != Google::Apis::ClientError ||
                 gptvcError.status_code != 404
             )
            raise gptvcError
          end
          final
        end
      end

    version_codes.max
  end

  desc 'Build'
  private_lane :build do |options|
    download_s3_assets
    version_code_tracks = options.fetch(:version_code_tracks, ['alpha'])
    current_version_code =
      latest_googleplay_version_code(
        package_name: options[:package_name],
        tracks: version_code_tracks,
      ).to_i
    version_code = current_version_code + 1

    write_changelog(version_code: version_code)

    package = load_json(json_path: '../package.json')
    version_number = package['version']

    version_name = "#{version_number}"
    enable_sdk_logging = options[:enable_sdk_logging]

    properties = {
      'versionCode' => version_code,
      'versionName' => version_name,
    }

    build_flavour_option = options[:build_flavor]

    gradle(
      task: 'bundle',
      flavor: build_flavour_option,
      build_type: 'Release',
      properties: properties,
      flags: '--no-daemon --max-workers 2',
    )

    version_code
  end

  desc 'Slack Error Message'
  private_lane :slack_error do |options|
    slack(
      message: 'An error has occurred',
      success: false,
      attachment_properties: {
        fields: [{ title: 'Details', value: options[:details] }],
      },
    )
  end

  desc 'Alpha Build'
  lane :alpha_build do
    version =
      build(
        build_name: 'NonaTemplate',
        build_flavor: 'Prod',
        package_name: 'com.nonatemplate',
        enable_sdk_logging: true,
        track: 'alpha',
        version_code_tracks: %w[alpha internal production preproduction],
      )
    version
  end

  desc 'Alpha Deploy'
  lane :alpha_deploy do
    begin
      gradle(task: 'clean')
      ENV['SPLIT_BUILDS'] = 'true'
      version = alpha_build

      upload_to_play_store(
        track: 'alpha',
        json_key_data: ENV['GOOGLE_PLAY_KEY'],
        metadata_path: './fastlane/metadata/android',
      )

      slack(
        message:
          "New Alpha build(#{version}) available on Google Play",
      )
    rescue => exception
      slack_error(details: exception.message)
    end
  end

  desc 'Production Build'
  lane :production_build do
    version =
      build(
        build_name: 'NonaTemplate',
        build_flavor: 'Prod',
        package_name: 'com.nonatemplate',
        enable_sdk_logging: false,
        track: 'Preproduction',
        version_code_tracks: %w[alpha beta internal production preproduction],
      )
    version
  end

  desc 'Production deploy'
  lane :production_deploy do
    begin
      gradle(task: 'clean')
      ENV['SPLIT_BUILDS'] = 'true'
      version = production_build

      upload_to_play_store(
        track: 'Preproduction',
        metadata_path: './fastlane/metadata/android',
        json_key_data: ENV['GOOGLE_PLAY_KEY'],
      )

      slack(
        message:
          "New Production build(#{version}) available on Google Play",
      )
    rescue => exception
      slack_error(details: exception.message)
    end
  end
end
