<?php

function diy_product_affilinet_trigger_sync() {
  $queue = DrupalQueue::get('diy_product_affilinet_sync');

  // We should check if there are items in the queue
  // If so, dont trigger it
  $queue_items_count = $queue->numberOfItems();

  if($queue_items_count > 0) {
    $text = t('There are %items left in affilinet queue. Did not trigger another run.', array('%items' => $queue_items_count));
    diy_product_log($text, WATCHDOG_ERROR);
    drupal_set_message($text);
    return 0;
  }

  $aff = new DiyAffHandler();
  $aff->login();

  if ($shops = $aff->getShopList()) {
    foreach ($shops as $shop) {

      // DEV
      //if(!in_array($shop->ShopId, array(1557, 4361))) {
      //  continue;
      //}

      $shop_nid = $aff->handleShop($shop);
      $categories = $aff->getCategoriesForShop($shop);

      if(is_array($categories)) {
        foreach ($categories as $category) {

          // DEV
          //if(!in_array($category->Id, array(12298326, 237885))) {
          //  continue;
          //}

          diy_product_log(t('Job add (%count): %shop, %category', array(
            '%shop' => $shop->ShopTitle,
            '%category' => $category->Title,
            '%count' => $category->ProductCount
          )));

          $queue->createItem(array(
            'shop' => $shop,
            'shop_nid' => $shop_nid,
            'category' => $category
          ));


        }
      }
    }

    return count($shops);
  }
}

/**
 * Worker callback for cron_queue_info.
 */
function diy_product_affilinet_sync_action($data) {
  // Things to do
  $aff = new DiyAffHandler();
  $aff->login();

  if($products = $aff->getProductsForShop($data['shop'], $data['category'])) {
    if(is_array($products->Products->Product)) {
      foreach($products->Products->Product as $product) {

        // DEV
        //if($product->ProductId != '678839776') {
          //continue;
        //}

        $aff->handleProduct($product, $data['shop_nid']);
      }
    }
  }

  diy_product_log(t('Job worked (%count): %shop, %category', array(
    '%shop' => $data['shop']->ShopTitle,
    '%category' => $data['category']->Title,
    '%count' => $data['category']->ProductCount
  )));
}

/**
 * Search for products, with given ean
 * Returns Uniform format, @see diy_products table
 */
function diy_product_affilinet_search_price_items($ean, $product) {
  $affHandler = new DiyAffHandler();
  $affHandler->login();

  $return_items = array();
  $price_items = $affHandler->searchProducts($ean);

  // search for new price items via affilinet
  if(is_array($price_items)) {
    foreach($price_items as $price_item) {
      if($product_data = $affHandler->getProductFields($price_item)) {
        $return_items[] = $product_data;
      } else {
        diy_product_log('Shop not found for affilinet shop id ' . $price_item->ShopId, WATCHDOG_ERROR);
      }
    }

    return $return_items;
  }

  return false;
}