<?php

/**
 * Triggers the sync
 */
function diy_product_bot_trigger_sync() {
  $queue = DrupalQueue::get('diy_product_bot_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 bot queue. Did not trigger another run.', array('%items' => $queue_items_count));
    diy_product_log($text, WATCHDOG_ERROR);
    drupal_set_message($text);
    return 0;
  }

  if($shops = diy_product_bot_get_shops()) {

    foreach($shops as $shop) {
      if($field_bot_xml_link = field_get_items('node', $shop, 'field_bot_xml_link')) {
        $url = $field_bot_xml_link[0]['url'];
        $xml = simplexml_load_file($url);

        // there are items in here
        if(count($xml)) {

          $items = array();
          foreach($xml as $item) {
            array_push($items, $item->asXML());
          }

          // maybe there are huge xml files, so lets chunk it arrays of 100 items each
          if($products = array_chunk($items, 100)) {

            // and now add the chunks to the queue
            foreach($products as $product_chunk) {
              $queue->createItem(array(
                'shop' => $shop,
                'products' => $product_chunk,
              ));
            }
          }

        }
      }
    }

    return count($shops);
  }

  return 0;
}


/**
 * Returns list of shops with have xml links attached
 */
function diy_product_bot_get_shops() {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'shop')
    ->propertyCondition('status', 1)
    ->fieldCondition('field_bot_xml_link', 'url', '', '<>')
    ->addMetaData('account', user_load(1));

  $result = $query->execute();

  if(isset($result['node'])) {
    $shop_items_nids = array_keys($result['node']);
    $shop_items = entity_load('node', $shop_items_nids);

    return $shop_items;
  }

  return false;
}

/**
 * Worker callback for cron_queue_info.
 */
function diy_product_bot_sync_action($data) {
  $shop = $data['shop'];
  $products = $data['products'];

  $bot = new DiyBotHandler();

  if(is_array($products)) {
    foreach($products as $product) {
      $product = simplexml_load_string($product);

      $bot->handleProduct($product, $shop);
    }
  }

  diy_product_log(t('Job worked (%count): %shop', array(
    '%shop' => $shop->title,
    '%count' => count($products)
  )));
}