# Copyright © 2017 Applause Inc. All rights reserved.

namespace :version_number do

desc "Removes suffix from version string in Info.plist file"
task :remove_suffix, [:setup_name] do |t, args|
              setup_name = args[:setup_name]
              setup = BuildConfiguration.load(setup_name)
  plist_path = setup.release_configuration.plist
  version = Plist.version(plist_path)
  version_without_suffix = version_without_suffix(version)
  set_version(plist_path, version_without_suffix)
end

desc "Updates build number to current commits count"
task :update_sdk_build_version, [:setup_name] do |t, args|
              setup_name = args[:setup_name]
  update_build_number_for_setup(setup_name)
end

desc "Updates test apps versions and build numbers to values from SDK"
task :update_test_apps_versions, [:setup_name] do |t, args|
              setup_name = args[:setup_name]
  set_test_apps_versions(setup_name)
  update_test_app_code_version(setup_name)
end

def update_build_number_to_commits_count(info_plist_path)
      commits_count = `git rev-list HEAD --count`.strip
      result = Plist.set_build_number("#{info_plist_path}", "#{commits_count}")
      if result.length > 0
              puts "Error: #{result}"
      end
end

private
def update_test_app_code_version(setup_name)
              setup = BuildConfiguration.load(setup_name)
  plist_path = setup.release_configuration.plist
  version = Plist.version(plist_path)
  build_number = Plist.build_number(plist_path)
  code_files = setup.release_configuration.test_apps_version_code_files
  code_files.each { |file|
    update_code_file_version(file, "#{version} (#{build_number})")
  } unless code_files.nil?
end

private
def update_code_file_version(file_path, version)
  text = File.read(file_path)
  new_contents = text.gsub("###VERSION###", version)
  File.open(file_path, "w") { |file| file.puts new_contents }
end

private
def set_test_apps_versions(setup_name)
              setup = BuildConfiguration.load(setup_name)
  plist_path = setup.release_configuration.plist
  version = Plist.version(plist_path)
  build_number = Plist.build_number(plist_path)
  test_apps_plists = setup.release_configuration.test_apps_plists
  test_apps_plists.each { |plist|
    update_application_version(plist, version, build_number)
  } unless test_apps_plists.nil?
end

private
def update_build_number_for_setup(setup_name)
  setup = BuildConfiguration.load(setup_name)
  plist_path = setup.release_configuration.plist
  update_build_number_to_commits_count(plist_path)
end

private
def version_without_suffix(version)
  return version.split("-")[0]
end

private
def update_application_version(info_plist_path, version, build_number)
  Plist.set_version(info_plist_path, version)
  Plist.set_build_number(info_plist_path, build_number)
end

end