require_relative "../helpers/git"
require_relative "../helpers/config"
require_relative "../helpers/pretty_table"

module Fastlane
  module Actions
    class SyncDevicesAction < Action
      def self.run(params)
        Tempfile.open("device_uuids.txt") do |file|
          UI.message("Syncing device uuids from Firebase...")
          other_action.firebase_app_distribution_get_udids(
            project_number: params[:firebase_project_number],
            output_file: file.path,
            service_credentials_json_data: other_action.firebase_credentials
          )
          devices = if File.exist?(file.path)
            file.read.split("\n").map{ |line| line.match(/^(?<uuid>[0-9a-z\-]+)\s+(?<email>[^\s]+)\s+-\s+(?<device>.+)\s+ios$/) }.reject{ |line| line.nil? }.map do |line|
              {
                email: line[:email],
                uuid: line[:uuid],
                device: line[:device]
              }
            end
          else
            []
          end

          UI.message("Found #{devices.count.to_s.cyan} device UUIDs in Firebase")

          unless devices.count > 0
            return
          end

          PrettyTable.print(data: devices, title: "Device UUIDs")

          UI.message("Registering devices in App Store Connect...")
          other_action.register_devices(
            devices_file: file.path,
            api_key: other_action.testflight_credentials
          )
          UI.success("Successfully registered devices in App Store Connect!")
        end
      end

      #####################################################
      # @!group Documentation
      #####################################################

      def self.description
        "Sync device UUIDs from Firebase and register them in App Store Connect"
      end

      def self.available_options
        [
          FastlaneCore::ConfigItem.new(
            key: :firebase_project_number,
            description: "Firebase project number",
            env_name: "FIREBASE_PROJECT_NUMBER",
            verify_block: proc do |value|
              UI.user_error!("Invalid firebase project number") if value.empty?
            end
          ),
        ]
      end

      def self.is_supported?(platform)
        [:ios, :macos].include?(platform)
      end
    end
  end
end
