<?php
/**
 * @file
 * Code for the DIY Tools feature.
 */

include_once 'diy_tools.features.inc';

/**
 * Implements hook_entity_info_alter().
 */
function diy_tools_entity_info_alter(&$entity_info) {
  $entity_info['node']['view modes']['embed_tools'] = array(
    'label' => t('Tools embed'),
    'custom settings' => TRUE,
  );

  $entity_info['node']['view modes']['embed_product'] = array(
    'label' => t('Product embed'),
    'custom settings' => TRUE,
  );
}

/**
 * Implements hook_preprocess_node().
 */
function diy_tools_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'embed_tools') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__embed_tools';
    $vars['classes_array'][] = 'node-embed-tools';
  }

  if($vars['view_mode'] == 'full') {
    $vars['classes_array'][] = 'node-full';
  }

  if($vars['view_mode'] == 'embed_product') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__embed_product';
    $vars['classes_array'][] = 'node-embed-product';
  }

  if($vars['view_mode'] == 'slider') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['type'] . '__slider';
    $vars['classes_array'][] = 'node-slider';
  }
}

/**
 * Implements HOOK_block_info().
 */
function diy_tools_block_info() {

  $blocks['diy_tools_products'] = array(
    'info' => t('DIY Tools products'),
  );

  $blocks['diy_tools_products_partner'] = array(
    'info' => t('DIY Tools products partner'),
  );


  return $blocks;
}

/**
 * Implements HOOK_block_view().
 */
function diy_tools_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'diy_tools_products':
      $block['content'] = diy_tools_products_block();
      $block['subject'] = t('Used products');
      break;
    case 'diy_tools_products_partner':
      $block['content'] = diy_tools_products_block(true);
      $block['subject'] = t('Recommended products');
      break;

  }

  return $block;
}

/**
 * Implements HOOK_preprocess_block().
 */
function diy_tools_preprocess_block(&$vars) {
  if(in_array($vars['block']->delta, array('diy_tools_products', 'diy_tools_products_partner'))) {
    $vars['classes_array'][] = 'sidebar-generic';
  }
}

/**
 * Products block
 */
function diy_tools_products_block($only_partner = false) {
  $node = menu_get_object();
  if(!$node || $node->type != 'article') {
    return;
  }

  if($only_partner) {
    $products = diy_tools_get_article_products_partner($node);

    shuffle($products);
    $products = array_slice($products, 0, 5);
  } else {
    $products = diy_tools_get_article_products($node);
  }

  $items = array();
  foreach($products as $product) {
    $product = node_load($product);

    $config = array(
      'title' => l(truncate_utf8($product->title, 34, false, true), 'node/' . $product->nid)
    );

    if($field_tool_material = field_get_items('node', $product, 'field_tool_material')) {
      $tm = node_load($field_tool_material[0]['nid']);
      $config += array('category' => truncate_utf8($tm->title, 17, false, true));
    }

    $image_config = diy_code_get_image(array(
      'node' => $product,
      'upload' => 'field_image'
    ));

    if($image_config) {
      $image_config += array('preset' => 'product_image_sidebar');
      $image = l(theme('diy_code_image', array('image' => $image_config)), 'node/' . $product->nid, array('html' => true));

      $config += array('image' => $image);
    }

    $items[] = array(
      'data' => (theme('diy_tools_sidebar_item', $config)),
      'class' => array('views-row')
    );
  }

  if(empty($items)) {
    return;
  }

  return theme_item_list(array(
    'type' => 'ul',
    'title' => NULL,
    'attributes' => array(),
    'items' => $items
  ));
}

/**
 * Implements HOOK_theme().
 */
function diy_tools_theme($existing, $type, $theme, $path) {
  return array(
    'diy_tools_sidebar_item' => array(
      'template' => 'sidebar-item',
      'path' => drupal_get_path('module', 'diy_tools') . '/templates',
      'variables' => array(
        'title' => NULL,
        'category' => NULL,
        'image' => NULL
      )
    ),
  );
}

/** 
 * Helper function for retrieving avg price for tools
 */
function diy_tools_get_price($values) {
  if(!empty($values)) {
    $price = array_sum($values) / count($values);
    $sum = number_format($price, 2, ',', '.');
    
    return $sum;
  }
  
  return FALSE;
}

/**
 * Helper functions to get products for one article
 */
function diy_tools_get_article_products($article) {
  $products = array();

  $fcis = _diy_tools_get_article_tm_collections($article);

  if(!empty($fcis)) {
    foreach($fcis as $fcid) {
      if($field_collection = field_collection_item_load($fcid)) {
        if($field_product = field_get_items('field_collection_item', $field_collection, 'field_product')) {

          if($product = node_load($field_product[0]['nid'])) {

            $products[] = $product->nid;

            // https://diybook.atlassian.net/browse/DIY-391?focusedCommentId=16501&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-16501
            #if($field_promote = field_get_items('node', $product, 'field_promote')) {
            #  if($field_promote[0]['value'] == 1) {
            #    $products[] = $product->nid;
            #  }
            #}
          }
        }
      }
    }
  }

  return diy_code_filter_nids_domain($products);
}

function diy_tools_get_article_products_partner($article) {
  $fcis = _diy_tools_get_article_tm_collections($article);

  $tm_with_product = array();
  $tm_without_product = array();

  if(!empty($fcis)) {
    foreach($fcis as $fcid) {
      if($field_collection = field_collection_item_load($fcid)) {
        $has_product = false;

        if($field_product = field_get_items('field_collection_item', $field_collection, 'field_product')) {
          $nid_field_product = $field_product[0]['nid'];
          
          if(diy_code_filter_nids_domain(array($nid_field_product))) {
            $has_product = true;
          }
          
        }

        if($field_collection->field_name == 'field_tools_tools') {
          if($field_tool = field_get_items('field_collection_item', $field_collection, 'field_tool')) {
            $tm_id = $field_tool[0]['nid'];
          }
        } else if($field_collection->field_name == 'field_tools_materials') {
          if($field_material = field_get_items('field_collection_item', $field_collection, 'field_material')) {
            $tm_id = $field_material[0]['nid'];
          }
        }

        if($has_product) {
          $tm_with_product[] = $tm_id;
        } else {
          $tm_without_product[] = $tm_id;
        }
      }
    }
  }

  $tm = array_diff($tm_without_product, $tm_with_product);

  if(!empty($tm)) {
    return diy_tools_tm_get_products($tm, true);
  }

  return array();
}

function diy_tools_tm_get_products($tm_nids, $only_promoted = false) {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
    ->entityCondition('bundle', 'product')
    ->propertyCondition('status', NODE_PUBLISHED)
    ->fieldCondition('field_tool_material', 'nid', $tm_nids, 'IN')
    ->addMetaData('account', user_load(1)); // Run the query as user 1.

  if($only_promoted) {
    $query->fieldCondition('field_promote', 'value', 1, '=');
  }

  $result = $query->execute();
  if (isset($result['node'])) {
    $nids_db = array_keys($result['node']);
    return diy_code_filter_nids_domain($nids_db);
  }

  return array();
}

function _diy_tools_get_article_tm_collections($article) {
  $fcis = array();

  foreach(array('field_tools_materials', 'field_tools_tools') as $field_key) {
    if($field = field_get_items('node', $article, $field_key)) {
      foreach($field as $item) {
        $fcis[] = $item['value'];
      }
    }
  }

  return $fcis;
}

function _diy_tools_get_mu_text($value) {

  switch ($value) {
    case 1:
      $label = t('pieces');
      break;
    case 2:
      $label = t('square meter');
      break;
    case 3:
      $label = t('cubic meter');
      break;
    case 4:
      $label = t('linear meter');
      break;
    case 5:
      $label = t('litre');
      break;
    case 6:
      $label = t('package');
      break;
    case 7:
      $label = t('kilogram');
      break;
    case 8:
      $label = t('gram');
      break;
    case 9:
      $label = t('ton');
      break;
    default:
      $label = t('n/a');
  }

  return $label;
}