# Copyright 2018 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

defmodule Mix.Tasks.GoogleApis.Publish do
  use Mix.Task
  require Logger

  @shortdoc "Publish clients"

  def run([only]) do
    only
    |> GoogleApis.ApiConfig.load()
    |> publish()
  end

  def run(_) do
    GoogleApis.ApiConfig.load_all()
    |> Enum.uniq_by(fn api -> api.name end)
    |> publish()
  end

  defp publish(apis) do
    failed_list = Enum.reduce(apis, [], fn api, acc ->
      case GoogleApis.publish(api) do
        {:ok, _} -> acc
        {:error, _} -> [api.name | acc]
      end
    end)
    if Enum.empty?(failed_list) do
      Logger.info("All publishes successful")
    else
      failed_str = Enum.join(failed_list, ", ")
      Mix.raise("Failed to publish: #{failed_str}")
    end
  end
end
