   use GenServer
   use Farmbot.Logger
   alias Farmbot.System.ConfigStorage
+  import ConfigStorage, only: [update_config_value: 4, get_config_value: 3]
 
   # 30 minutes.
   @refresh_time 1.8e+6 |> round()

  def handle_info(:refresh, _old_timer) do
    auth_task = Application.get_env(:farmbot, :behaviour)[:authorization]
    {email, pass, server} = {fetch_email(), fetch_pass(), fetch_server()}
    # Logger.busy(3, "refreshing token: #{auth_task} - #{email} - #{server}")
    Farmbot.System.GPIO.Leds.led_status_err()
    case auth_task.authorize(email, pass, server) do
      {:ok, token} ->
        # Logger.success(3, "Successful authorization: #{auth_task} - #{email} - #{server}")
        ConfigStorage.update_config_value(:bool, "settings", "first_boot", false)
        ConfigStorage.update_config_value(:string, "authorization", "token", token)
        Farmbot.System.GPIO.Leds.led_status_ok()
        if ConfigStorage.get_config_value(:bool, "settings", "auto_sync") do
          Farmbot.Repo.flip()
        end
        restart_transports()
        refresh_timer(self())
      {:error, reason} ->
        Logger.error(1, "Token failed to reauthorize: #{auth_task} - #{email} - #{server} #{inspect reason}")
        refresh_timer(self(), 30_000)
    end
  end

  end

  defp fetch_email do
    email = get_config_value(:string, "authorization", "email")
    email || raise "No email provided."
  end

  defp fetch_pass do
    pass = get_config_value(:string, "authorization", "password")
    pass || raise "No password provided."
  end

  defp fetch_server do
    server = get_config_value(:string, "authorization", "server")
    server || raise "No server provided."
  end
end
