প্রকাশকের প্রোফাইল দেখুন

আপনি তাদের PublisherProfile প্রকাশকের সম্পর্কে তথ্য দেখতে নিম্নলিখিত পদ্ধতিগুলি ব্যবহার করতে পারেন৷

স্বতন্ত্র প্রোফাইল পান

আপনি একটি নির্দিষ্ট প্রকাশক সনাক্ত করতে buyers.publisherProfiles.get পদ্ধতি ব্যবহার করতে পারেন।

উদাহরণস্বরূপ, যখন আপনি একজন প্রকাশকের কাছ থেকে একটি প্রস্তাব পান, আপনি আরও তথ্য দেখতে প্রকাশকের PublisherProfile পেতে পারেন।

নিম্নলিখিতগুলি দেখায় যে আপনি কীভাবে একটি পৃথক PublisherProfile get পদ্ধতির মাধ্যমে পুনরুদ্ধার করতে পারেন:

বিশ্রাম

অনুরোধ

GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/publisherProfiles/PP12345?alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

প্রতিক্রিয়া

{
  "name":"buyers/12345678/publisherProfiles/PP12345",
  "displayName":"Mars News",
  "logoUrl":"//www.gstatic.com/adx/customerlogos/999221114/0/1234567890.jpg",
  "directDealsContact":"advertising@marsnews.com",
  "programmaticDealsContact":"advertising@marsnews.com",
  "samplePageUrl":"http://www.news.mars/ ",
  "overview":"Mars news is the top news organization in the United Federation of Mars, covering a broad range of subjects such as local politics, the interplanetary exchange, and the latest xenoarchaeological discoveries.\n",
  "pitchStatement":"Mars News is the premier Mars news network, and the most trusted source of  Mars news in the Milky Way. Reach our multicultural and multispecies community of highly educated Martians and friends of Mars from abroad.",
  "topHeadlines":[
     "Most trusted news source on Mars",
     "Journalistic integrity that is recognized across the galaxy",
     "Incredible interplanetary reach"
  ],
  "isParent":true
}

সি#

/* Copyright 2022 Google LLC
 *
 * 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.
 */

using Google.Apis.AuthorizedBuyersMarketplace.v1;
using Google.Apis.AuthorizedBuyersMarketplace.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1.Buyers.PublisherProfiles
{
    /// <summary>
    /// Gets a single publisher profile for the given buyer and publisher profile ID.
    /// </summary>
    public class GetPublisherProfiles : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public GetPublisherProfiles()
        {
            mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example gets a specific publisher profile for a buyer account.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id", "publisher_profile_id"};
            bool showHelp = false;

            string accountId = null;
            string publisherProfileId = null;

            OptionSet options = new OptionSet {
                "Get a publisher profile for a given buyer and publisher profile ID.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "publisherProfiles resource is being accessed. This will be used to " +
                     "construct the name used as a path parameter for the publisherProfiles.get " +
                     "request."),
                    a => accountId = a
                },
                {
                    "p|publisher_profile_id=",
                    ("[Required] The resource ID of the buyers.publisherProfiles resource that " +
                     "is being accessed. This will be used to construct the name used as a " +
                     "path parameter for the publisherProfiles.get request."),
                    p => publisherProfileId = p
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if (showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set optional arguments.
            parsedArgs["account_id"] = accountId;
            parsedArgs["publisher_profile_id"] = publisherProfileId;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string publisherProfileId = (string) parsedArgs["publisher_profile_id"];
            string name = $"buyers/{accountId}/publisherProfiles/{publisherProfileId}";

            BuyersResource.PublisherProfilesResource.GetRequest request =
                mkService.Buyers.PublisherProfiles.Get(name);
            PublisherProfile response = null;

            Console.WriteLine("Getting publisher profile with name: {0}", name);

            try
            {
                response = request.Execute();
            }
            catch (Exception exception)
            {
                throw new ApplicationException(
                    $"Marketplace API returned error response:\n{exception.Message}");
            }

            Utilities.PrintPublisherProfile(response);
        }
    }
}

জাভা

/*
 * Copyright 2022 Google LLC
 *
 * 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
 *
 *    https://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.
 */

package com.google.api.services.samples.authorizedbuyers.marketplace.v1.buyers.publisherProfiles;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.PublisherProfile;
import com.google.api.services.samples.authorizedbuyers.marketplace.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * This sample illustrates how to get a publisher profile for the given buyer and publisher profile
 * ID.
 */
public class GetPublisherProfiles {

  public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
    Long accountId = parsedArgs.getLong("account_id");
    String publisherProfileId = parsedArgs.getString("publisher_profile_id");
    String name = String.format("buyers/%d/publisherProfiles/%s", accountId, publisherProfileId);

    PublisherProfile publisherProfile = null;

    try {
      publisherProfile = marketplaceClient.buyers().publisherProfiles().get(name).execute();
    } catch (IOException ex) {
      System.out.printf("Marketplace API returned error response::%n%s", ex);
      System.exit(1);
    }

    System.out.printf(
        "Found publisher profile with ID \"%s\" for buyer account ID '%d'::%n",
        publisherProfileId, accountId);
    Utils.printPublisherProfile(publisherProfile);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("GetPublisherProfiles")
            .build()
            .defaultHelp(true)
            .description(("Get a publisher profile for the given buyer and publisher profile ID."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the publisher profile resource "
                + "is being accessed. This will be used to construct the parent used as a path "
                + "parameter for the publisherProfiles.get request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-p", "--publisher_profile_id")
        .help(
            "The resource ID of the buyers.publisherProfiles resource that is being accessed. "
                + "This will be used to construct the name used as a path parameter for the "
                + "publisherProfiles.get request.")
        .required(true);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    AuthorizedBuyersMarketplace client = null;
    try {
      client = Utils.getMarketplaceClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Marketplace API service::%n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport::%n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

পাইথন

#!/usr/bin/python
#
# Copyright 2021 Google Inc. All Rights Reserved.
#
# 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.

"""Gets a single publisher profile for the given account and profile IDs."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_PUB_PROFILE_NAME_TEMPLATE = 'buyers/%s/publisherProfiles/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
DEFAULT_PUB_PROFILE_RESOURCE_ID = 'ENTER_PUB_PROFILE_RESOURCE_ID_HERE'


def main(marketplace, args):
    account_id = args.account_id
    publisher_profile_id = args.publisher_profile_id

    print(f'Get publisher profile "{publisher_profile_id}" for account '
          f'"{account_id}":')
    try:
        # Construct and execute the request.
        response = marketplace.buyers().publisherProfiles().get(
            name=_PUB_PROFILE_NAME_TEMPLATE % (
                account_id, publisher_profile_id)).execute()
    except HttpError as e:
        print(e)
        sys.exit(1)

    pprint.pprint(response)


if __name__ == '__main__':
    try:
        service = util.get_service(version='v1')
    except IOError as ex:
        print(f'Unable to create marketplace service - {ex}')
        print('Did you specify the key file in util.py?')
        sys.exit(1)

    parser = argparse.ArgumentParser(
        description=('Get a publisher profile for the given buyer account ID '
                     'and publisher profile ID.'))
    # Required fields.
    parser.add_argument(
        '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
        help=('The resource ID of the buyers resource under which the '
              'publisherProfiles resource is being accessed. This will be used '
              'to construct the name used as a path parameter for the '
              'publisherProfiles.get request.'))
    parser.add_argument(
        '-p', '--publisher_profile_id', default=DEFAULT_PUB_PROFILE_RESOURCE_ID,
        help=('The resource ID of the buyers.publisherProfiles resource that '
              'is being accessed. This will be used to construct the name used '
              'as a path parameter for the publisherProfiles.get request.'))

    main(service, parser.parse_args())

একাধিক প্রকাশক প্রোফাইল তালিকা করুন

আপনি buyers.publisherProfiles.list পদ্ধতি ব্যবহার করতে পারেন সমস্ত প্রকাশকের প্রোফাইলের মাধ্যমে পৃষ্ঠা করতে, অথবা filter প্যারামিটার ব্যবহার করে প্রকাশক প্রোফাইলের একটি উপসেট খুঁজে পেতে।

list পদ্ধতির সাহায্যে আপনি কীভাবে প্রকাশকের প্রোফাইলের একটি তালিকা পুনরুদ্ধার করতে পারেন তা নিম্নলিখিতটি দেখায়:

বিশ্রাম

অনুরোধ

GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/publisherProfiles?pageSize=3&alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

প্রতিক্রিয়া

{
  "publisherProfiles":[
     {
        "name":"buyers/12345678/publisherProfiles/PP12345",
        "displayName":"Mars News",
        "logoUrl":"//www.gstatic.com/adx/customerlogos/999221114/0/1234567890.jpg",
        "directDealsContact":"advertising@marsnews.com",
        "programmaticDealsContact":"advertising@marsnews.com",
        "samplePageUrl":"http://www.news.mars/ ",
        "overview":"Mars news is the top news organization in the United Federation of Mars, covering a broad range of subjects such as local politics, the interplanetary exchange, and the latest xenoarchaeological discoveries.\n",
        "pitchStatement":"Mars News is the premier Mars news network, and the most trusted source of Mars news in the Milky Way. Reach our multicultural and multispecies community of highly educated Martians and friends of Mars from abroad.",
        "topHeadlines":[
           "Most trusted news source on Mars",
           "Journalistic integrity that is recognized across the galaxy",
           "Incredible interplanetary reach"
        ],
        "isParent":true
     },
     {
        "name":"buyers/12345678/publisherProfiles/PP54321",
        "displayName":"Red Planet",
        "domains":[
           "redplanet.mars",
           "luxurytravel.mars"
        ],
        "logoUrl":"//www.gstatic.com/adx/customerlogos/877235551/1/2165203912871.jpg",
        "directDealsContact":"advertising@redplanet.mars",
        "programmaticDealsContact":"advertising@redplanet.mars",
        "samplePageUrl":"https://redplanet.mars/travel",
        "overview":"Red Planet is dedicated to promoting Mars tourism with extensive travel guides to help spacefarers find the best cultural, historical, or natural travel destinations across the planet.\n",
        "pitchStatement":"Find your audience of intrepid space explorers today.",
        "topHeadlines":[
           "Leader in rapidly growing Mars travel industry",
           "Travel guides trusted across the galaxy",
           "Quality travel guides for the adventurous"
        ]
     },
     {
        "name":"buyers/12345678/publisherProfiles/PP67890",
        "displayName":"Mars Media Ltd",
        "isParent":true
     }
  ],
  "nextPageToken":"CAMQ7rnIhufQ9gIY7rnIhufQ9gI="
}

সি#

/* Copyright 2022 Google LLC
 *
 * 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.
 */

using Google.Apis.AuthorizedBuyersMarketplace.v1;
using Google.Apis.AuthorizedBuyersMarketplace.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1.Buyers.PublisherProfiles
{
    /// <summary>
    /// Lists publisher profiles for a given buyer account ID.
    /// </summary>
    public class ListPublisherProfiles : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListPublisherProfiles()
        {
            mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example lists publisher profiles for a given buyer account.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id"};
            bool showHelp = false;

            string accountId = null;
            string filter = null;
            int? pageSize = null;

            OptionSet options = new OptionSet {
                "List publisher profiles for the given buyer account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "publisherProfiles resource is being accessed. This will be used to " +
                     "construct the parent used as a path parameter for the " +
                     "publisherProfiles.list request."),
                    a => accountId = a
                },
                {
                    "p|page_size=",
                    ("The number of rows to return per page. The server may return fewer rows " +
                     "than specified."),
                    (int p) => pageSize =  p
                },
                {
                    "f|filter=",
                    ("Query string to filter publisher profiles. If no filter is specified, all " +
                    "publisher profiles will be returned. By default, no filter will be set by " +
                    "this example."),
                    f => filter = f
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if (showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs["account_id"] = accountId;
            parsedArgs["pageSize"] = pageSize ?? Utilities.MAX_PAGE_SIZE;
            parsedArgs["filter"] = filter;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string parent = $"buyers/{accountId}";
            string pageToken = null;

            Console.WriteLine(@"Listing publisher profiles for buyer account ""{0}""", parent);
            do
            {
                BuyersResource.PublisherProfilesResource.ListRequest request =
                    mkService.Buyers.PublisherProfiles.List(parent);
                request.Filter = (string) parsedArgs["filter"];
                request.PageSize = (int) parsedArgs["pageSize"];
                request.PageToken = pageToken;

                ListPublisherProfilesResponse page = null;

                try
                {
                    page = request.Execute();
                }
                catch (Exception exception)
                {
                    throw new ApplicationException(
                        $"Marketplace API returned error response:\n{exception.Message}");
                }

                var publisherProfiles = page.PublisherProfiles;
                pageToken = page.NextPageToken;

                if (publisherProfiles == null)
                {
                    Console.WriteLine("No publisher profiles found for buyer account.");
                }
                else
                {
                    foreach (PublisherProfile publisherProfile in publisherProfiles)
                    {
                        Utilities.PrintPublisherProfile(publisherProfile);
                    }
                }
            }
            while(pageToken != null);
        }
    }
}

জাভা

/*
 * Copyright 2022 Google LLC
 *
 * 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
 *
 *    https://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.
 */

package com.google.api.services.samples.authorizedbuyers.marketplace.v1.buyers.publisherProfiles;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.ListPublisherProfilesResponse;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.PublisherProfile;
import com.google.api.services.samples.authorizedbuyers.marketplace.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/** This sample illustrates how to list publisher profiles for a given buyer account ID. */
public class ListPublisherProfiles {

  public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
    Long accountId = parsedArgs.getLong("account_id");
    Integer pageSize = parsedArgs.getInt("page_size");
    String parentBuyerName = String.format("buyers/%s", accountId);
    String pageToken = null;

    System.out.printf("Found publisher profiles for buyer Account ID '%d'::%n", accountId);

    do {
      List<PublisherProfile> publisherProfiles = null;

      try {
        ListPublisherProfilesResponse response =
            marketplaceClient
                .buyers()
                .publisherProfiles()
                .list(parentBuyerName)
                .setFilter(parsedArgs.getString("filter"))
                .setPageSize(pageSize)
                .setPageToken(pageToken)
                .execute();

        publisherProfiles = response.getPublisherProfiles();
        pageToken = response.getNextPageToken();
      } catch (IOException ex) {
        System.out.printf("Marketplace API returned error response::%n%s", ex);
        System.exit(1);
      }
      if (publisherProfiles == null) {
        System.out.println("No publisher profiles found.");
      } else {
        for (PublisherProfile publisherProfile : publisherProfiles) {
          Utils.printPublisherProfile(publisherProfile);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("ListPublisherProfiles")
            .build()
            .defaultHelp(true)
            .description(("Lists publisher profiles associated with the given buyer account."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the publisherProfiles resource "
                + "is being accessed. This will be used to construct the parent used as a path "
                + "parameter for the publisherProfiles.list request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-f", "--filter")
        .help(
            "Query string to filter publisher profiles. If no filter is specified, all "
                + "publisher profiles will be returned. By default, no filter will be set by this "
                + "example.");
    parser
        .addArgument("-p", "--page_size")
        .help(
            "The number of rows to return per page. The server may return fewer rows than "
                + "specified.")
        .setDefault(Utils.getMaximumPageSize())
        .type(Integer.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    AuthorizedBuyersMarketplace client = null;
    try {
      client = Utils.getMarketplaceClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Marketplace API service::%n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport::%n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

পাইথন

#!/usr/bin/python
#
# Copyright 2021 Google Inc. All Rights Reserved.
#
# 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.

"""This example lists publisher profiles for the specified buyer."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_BUYER_NAME_TEMPLATE = 'buyers/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'


def main(marketplace, args):
    account_id = args.account_id
    list_filter = args.filter
    page_size = args.page_size

    page_token = None
    more_pages = True

    print(f'Listing publisher profiles for buyer account: "{account_id}".')
    while more_pages:
        try:
            # Construct and execute the request.
            response = marketplace.buyers().publisherProfiles().list(
                parent=_BUYER_NAME_TEMPLATE % account_id, pageToken=page_token,
                filter=list_filter, pageSize=page_size).execute()
        except HttpError as e:
            print(e)
            sys.exit(1)

        pprint.pprint(response)

        page_token = response.get('nextPageToken')
        more_pages = bool(page_token)


if __name__ == '__main__':
    try:
        service = util.get_service(version='v1')
    except IOError as ex:
        print(f'Unable to create marketplace service - {ex}')
        print('Did you specify the key file in util.py?')
        sys.exit(1)

    parser = argparse.ArgumentParser(
        description='Lists publisher profiles for the given buyer account.')
    # Required fields.
    parser.add_argument(
        '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
        help=('The resource ID of the buyers resource under which the '
              'publisherProfiles resource is being accessed. This will be used '
              'to construct the parent used as a path parameter for the '
              'publisherProfiles.list request.'))
    # Optional fields.
    parser.add_argument(
        '-f', '--filter', default=None,
        help=('Query string to filter publisherProfiles. If no filter is '
              'specified, all profiles will be returned. By default, no filter '
              'will be set.'))
    parser.add_argument(
        '-p', '--page_size', default=util.MAX_PAGE_SIZE,
        help=('The number of rows to return per page. The server may return '
              'fewer rows than specified. A maximum of 500 results per page '
              'will be returned.'))

    main(service, parser.parse_args())