# This file contains the fastlane.tools configuration for Android
# 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

require 'json'
require 'base64'
require 'pathname'

default_platform(:android)

current_version_code = 1
playstore_track = "internal"
package_json = JSON.parse(File.read('../../package.json'))
keystorePath = Pathname.getwd.parent  + "../../playstore.keystore"

platform :android do

  lane :fetch_version_code do
    current_version_code = google_play_track_version_codes(
      package_name:  ENV['ANDROID_PACKAGE_NAME'],
      track: playstore_track,
      json_key_data: ENV['ANDROID_API_KEY_CONTENT']
    ).max
  end

  lane :fetch_highest_version_code do
    version_code_candidates = [1]
    tracks = ['production', 'beta', 'internal']
    tracks.each do |t|
      version_code_candidates += google_play_track_version_codes(
        package_name: ENV['ANDROID_PACKAGE_NAME'],
        track: t,
        json_key_data: Base64.decode64(ENV['ANDROID_API_KEY_CONTENT'])
      )
    end
    current_version_code = version_code_candidates.compact.max
    puts "Version code chosen for build lane: %d" % [current_version_code + 1] 
  end

  lane :build do
    fetch_highest_version_code
    android_set_version_name(
      version_name: package_json["version"],
    )
    android_set_version_code(
      version_code: current_version_code + 1,
    )
    gradle(
      task: "clean assemble",
      build_type: "Release",
      print_command: false,
      properties: {
        "android.injected.signing.store.file" => keystorePath.to_s,
        "android.injected.signing.store.password" => ENV['ANDROID_KEYSTORE_PASSWORD'],
        "android.injected.signing.key.alias" => ENV['ANDROID_KEYSTORE_KEY_ALIAS'],
        "android.injected.signing.key.password" => ENV['ANDROID_KEYSTORE_KEY_PASSWORD']
      }
    )
  end

  desc "Submit a new beta build to open beta testing track"
  lane :beta do
    playstore_track = "beta"

    build
    upload_to_play_store(
      track: playstore_track,
      json_key_data: Base64.decode64(ENV['ANDROID_API_KEY_CONTENT']),
      skip_upload_metadata: true,
      skip_upload_images: true,
      skip_upload_screenshots: true
    )
  end

  desc "Submit a new version to the Google Play"
  lane :release do
    playstore_track = "production"

    build
    upload_to_play_store(
      track: playstore_track,
      json_key_data: Base64.decode64(ENV['ANDROID_API_KEY_CONTENT']),
      skip_upload_metadata: true,
      skip_upload_images: true,
      skip_upload_screenshots: true
    )
  end
end
