# Path: oscar_mws/feeds/gateway.py
# def submit_product_feed(products, marketplaces, dry_run=False,
#                         operation_type=OP_TYPE_UPDATE):
#     """
#     Generate a product feed for the list of *products* and submit it to
#     Amazon. The submission ID returned by them is used to create a
#     FeedSubmission to log the progress of the submission as well as the
#     products that are handled as part of the submission.
# 
#     A list of *marketplaces* is also required that specify the Amazon
#     marketplaces to submit the product(s) to. The marketplaces have to be
#     part of the same merchant account and have to have the same language code
#     specified. If either of these restrictions is violated, the feed will be
#     rejected by Amazon.
# 
#     :param list products: list of Oscar products to be submitted
#     :param list marketplaces: list of AmazonMarketplaces to make the products
#         available on
#     :param boolean dry_run: flag to specify dry run mode. If ``True`` the XML
#         feed will be generated and printed to stdout instead of submitting it
#         to MWS. Default: ``False``.
#     :param str operation_type: the operation type for the MWS feed according to
#         the MWS documentation. Default: ``Update``.
# 
#     :rtype list: list of FeedSubmission objects created for the submitted MWS
#         feeds
# 
#     :raises MwsFeedError: if marketplaces aren't part of the same Amazon
#         merchant account.
#     :raises MWSError: if an error occurs while communicating with MWS.
#     """
#     merchant_ids = set([m.merchant_id for m in marketplaces])
#     marketplace_ids = [m.marketplace_id for m in marketplaces]
#     if len(merchant_ids) > 1:
#         raise MwsFeedError(
#             "Marketplaces of different merchant accounts specified. This "
#             "is invalid, please only use marketplaces for the same seller")
# 
#     submissions = []
#     for marketplace in marketplaces:
#         merchant = marketplace.merchant
#         logger.info(
#             "Updating {0} products for seller ID {1}".format(
#                 len(products), merchant.seller_id))
# 
#         writer = writers.ProductFeedWriter(merchant_id=merchant.seller_id)
#         for product in products:
#             writer.add_product(product)
#         xml_data = writer.as_string(pretty_print=dry_run)
# 
#         logger.debug("Product feed XML to be submitted:\n{0}".format(xml_data))
# 
#         if dry_run:
#             print xml_data
#             return
# 
#         feeds_api = get_merchant_connection(merchant.seller_id, 'feeds')
#         try:
#             response = feeds_api.submit_feed(
#                 feed=xml_data, feed_type=am.TYPE_POST_PRODUCT_DATA,
#                 marketplaceids=marketplace_ids or merchant.marketplace_ids)
#         except MWSError:
#             logger.error(
#                 "could not submit product feed to MWS", exc_info=1,
#                 extra={'seller_id': merchant.seller_id,
#                        'marketplace_id': marketplace.marketplace_id,
#                        'product_ids': [p.id for p in products],
#                        'feed_xml': xml_data})
#             raise
#         submission = handle_feed_submission_response(merchant, response.parsed,
#                                                      feed_xml=xml_data)
#         for product in products:
#             submission.submitted_products.add(product)
#         submissions.append(submission)
#     return submissions


from optparse import make_option
from django.db.models import get_model
from django.core.management.base import NoArgsCommand
from oscar_mws.feeds.gateway import submit_product_feed
Product = get_model('catalogue', 'Product')


class Command(NoArgsCommand):
    option_list = NoArgsCommand.option_list + (
        make_option(
            '--dry-run',
            action='store_true',
            dest='dry_run',
            default=False,
            help=('Do not submit the product feed put print the generated '
                  'XML to stdout.')
        ),
        make_option(
            '--seller-id',
            dest='seller_id',
            help=('Seller ID used to submit the product feed')
        ),
    )

    def handle_noargs(self, **options):
        # get all products without a ASIN assigned
        products = Product.objects.all()

        merchant_id = options.get('seller_id')

        if options.get('dry_run'):
            submit_product_feed(products, merchant_id, dry_run=True)
            return


# Path: oscar_mws/feeds/gateway.py
# def submit_product_feed(products, marketplaces, dry_run=False,
#                         operation_type=OP_TYPE_UPDATE):
#     """
#     Generate a product feed for the list of *products* and submit it to
#     Amazon. The submission ID returned by them is used to create a
#     FeedSubmission to log the progress of the submission as well as the
#     products that are handled as part of the submission.
# 
#     A list of *marketplaces* is also required that specify the Amazon
#     marketplaces to submit the product(s) to. The marketplaces have to be
#     part of the same merchant account and have to have the same language code
#     specified. If either of these restrictions is violated, the feed will be
#     rejected by Amazon.
# 
#     :param list products: list of Oscar products to be submitted
#     :param list marketplaces: list of AmazonMarketplaces to make the products
#         available on
#     :param boolean dry_run: flag to specify dry run mode. If ``True`` the XML
#         feed will be generated and printed to stdout instead of submitting it
#         to MWS. Default: ``False``.
#     :param str operation_type: the operation type for the MWS feed according to
#         the MWS documentation. Default: ``Update``.
# 
#     :rtype list: list of FeedSubmission objects created for the submitted MWS
#         feeds
# 
#     :raises MwsFeedError: if marketplaces aren't part of the same Amazon
#         merchant account.
#     :raises MWSError: if an error occurs while communicating with MWS.
#     """
#     merchant_ids = set([m.merchant_id for m in marketplaces])
#     marketplace_ids = [m.marketplace_id for m in marketplaces]
#     if len(merchant_ids) > 1:
#         raise MwsFeedError(
#             "Marketplaces of different merchant accounts specified. This "
#             "is invalid, please only use marketplaces for the same seller")
# 
#     submissions = []
#     for marketplace in marketplaces:
#         merchant = marketplace.merchant
#         logger.info(
#             "Updating {0} products for seller ID {1}".format(
#                 len(products), merchant.seller_id))
# 
#         writer = writers.ProductFeedWriter(merchant_id=merchant.seller_id)
#         for product in products:
#             writer.add_product(product)
#         xml_data = writer.as_string(pretty_print=dry_run)
# 
#         logger.debug("Product feed XML to be submitted:\n{0}".format(xml_data))
# 
#         if dry_run:
#             print xml_data
#             return
# 
#         feeds_api = get_merchant_connection(merchant.seller_id, 'feeds')
#         try:
#             response = feeds_api.submit_feed(
#                 feed=xml_data, feed_type=am.TYPE_POST_PRODUCT_DATA,
#                 marketplaceids=marketplace_ids or merchant.marketplace_ids)
#         except MWSError:
#             logger.error(
#                 "could not submit product feed to MWS", exc_info=1,
#                 extra={'seller_id': merchant.seller_id,
#                        'marketplace_id': marketplace.marketplace_id,
#                        'product_ids': [p.id for p in products],
#                        'feed_xml': xml_data})
#             raise
#         submission = handle_feed_submission_response(merchant, response.parsed,
#                                                      feed_xml=xml_data)
#         for product in products:
#             submission.submitted_products.add(product)
#         submissions.append(submission)
#     return submissions


# Path: oscar_mws/management/commands/mws_submit_product_feed.py
from optparse import make_option
from django.db.models import get_model
from django.core.management.base import NoArgsCommand
from oscar_mws.feeds.gateway import submit_product_feed

Product = get_model('catalogue', 'Product')


class Command(NoArgsCommand):
    option_list = NoArgsCommand.option_list + (
        make_option(
            '--dry-run',
            action='store_true',
            dest='dry_run',
            default=False,
            help=('Do not submit the product feed put print the generated '
                  'XML to stdout.')
        ),
        make_option(
            '--seller-id',
            dest='seller_id',
            help=('Seller ID used to submit the product feed')
        ),
    )

    def handle_noargs(self, **options):
        # get all products without a ASIN assigned
        products = Product.objects.all()

        merchant_id = options.get('seller_id')

        if options.get('dry_run'):
            submit_product_feed(products, merchant_id, dry_run=True)
            return


        submission = submit_product_feed(products, merchant_id)