# 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)
ENV_PATH = "../asset/app/.env"
ANDROID_VERSION_NAME = 'androidVersionName'
platform :android do
  desc "Deploy to internal test app"
  lane :internal do |options|
    versionNumberArrayLength = google_play_track_version_codes.length
    versionNumber = versionNumberArrayLength > 0 ? google_play_track_version_codes[0] : 1
  
    increment_version(version: options[:version])
    set_version_number(versionNumber: options[:versionNumber])
   
    versionName = get_version_name()
    flutter_build(versionName, versionNumber)
  end
  
  private_lane :set_version_number do |options|
    if options[:versionNumber] != nil 
      set_properties_value(
        key: ANDROID_VERSION_NAME,
        path: ENV_PATH,
        value: options[:versionNumber]
      )
    end
  end
  
  private_lane :increment_version do |options|
    if options[:version] != nil 
      increment_version_name_in_properties_file(
        key: ANDROID_VERSION_NAME,
        path: ENV_PATH,
        update_type: options[:version]
      )
    end
  end
  
  def get_version_name 
    return get_properties_value(
      key: ANDROID_VERSION_NAME,
      path: ENV_PATH
    )
  end
  
  def flutter_build(versionName, number)
    Dir.chdir('../../') do
      sh('flutter', 'packages', 'get')
      sh('flutter', 'clean')
      sh("flutter build appbundle --build-name=#{versionName} --build-number=#{number.to_s}")
    end
  end
  
  desc "Deploy a new version to the Google Play"
  lane :deploy do
    gradle(task: "clean assembleRelease")
    upload_to_play_store
  end
end
