/**

 Ações do Google Tag Manager / Google Merchant Center / Google Shopping
**/

/*Document Ready*/
$(function() {
  setTimeout(function () {
    let nome_pagina = $('body').attr('id');
    //console.log('Nome da Página (Id do Body): '+nome_pagina);

    if (nome_pagina === 'product') {
      let prod_id = $('meta[property="product:retailer_item_id"]').attr('content');
      let prod_name = $.trim($('meta[property="og:title"]').attr('content')).replace('\n','');
      let prod_price = $.trim($('meta[property="product:price:amount"]').attr('content')).replace('\n','');
      let prod_brand = $.trim($('meta[property="product:brand"]').attr('content')).replace('\n','');
      let prod_category = $.trim($('span[class="value feat8"]').html()).replace('\n','');
      let prod_variant = $.trim($('span[class="value feat6"]').html()).replace('\n','');
      let prod_quantity = $.trim($('#quantity_wanted').val()).replace('\n','');

      let product = {
        'id': prod_id,
        'name': prod_name,
        'price': prod_price,
        'brand': prod_brand,
        'category': prod_category,
        'variant': prod_variant,
        'list': 'Product Detail',
        'quantity': prod_quantity
      };

      // Medir as visualizações dos detalhes do produto
      // https://developers.google.com/tag-manager/enhanced-ecommerce#details
      /*dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
      dataLayer.push({
        'ecommerce': {
          'detail': {
            'actionField': {'list': product.list}, // 'detail' actions have an optional list property.
            'products': [{
              'name': product.name, // Name or ID is required.
              'id': product.id,
              'price': product.price,
              'brand': product.brand,
              'category': product.category,
              'variant': product.variant
            }]
          }
        }
      });*/

      // Adicionar um produto a um carrinho de compras
      // https://developers.google.com/tag-manager/enhanced-ecommerce#cart
      $('button.add-to-cart[data-button-action="add-to-cart"]').on('click', function () {
        let iso_code = $.trim(prestashop.currency.iso_code);

        dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.

        dataLayer.push({
          'event': 'add_to_cart',
          'ecommerce': {
                'currency': iso_code,
                'value': Number(product.price *  product.quantity).toFixed(2),
                'items':[
                    {
                        item_name:product.name,
                        item_id:product.id,
                        price:product.price,
                        item_brand:product.brand,
                        quantity:product.quantity
                    }
                ]
            }
          
        });
      });
    }

    if (nome_pagina === 'cart') {
      $('a.remove-from-cart').on('click', function () {
        let prod_id = $(this).attr('data-id-product');
        let prod_name = $.trim($('div.productremovebyid_'+prod_id+' a.label').html()).replace('\n','');
        let prod_price = $.trim($('span.product-price > span').html()).replace('&nbsp;','').replace('€','');
        let prod_brand = $.trim($('#prod_brand_for_id_'+prod_id).html());
        let prod_category = $.trim($('#prod_categ_for_id_'+prod_id).html());
        let prod_variant = $.trim($('.product-line-info.prod-features > span[class="value"]').html());
        let product = {
          'item_id': prod_id,
          'item_name': prod_name,
          'price': prod_price,
          'item_brand': prod_brand,
          'item_category': prod_category,
          'item_category': prod_variant
        };

        //console.log(product);

        // Measure the removal of a product from a shopping cart.
        dataLayer.push({ ecommerce: null }); // Clear the previous ecommerce object.
        dataLayer.push({
          'event': 'remove_from_cart',
          'items':[product]
        });
      });


    }

    if (nome_pagina === 'category' || nome_pagina === 'search') {
      //Se existir uma listagem
      if ($('#js-product-list').length > 0) {
        let products = [];
        $.each($('article'), function(key, value) {
          let prod_id = $(this).attr('data-id-product');
          let prod_name = $.trim($(this).find('meta[itemprop="description"]').attr('content')).replace('\n','');
          let prod_price = $.trim($(this).find('span[itemprop="price"]').attr('content')).replace('\n','');
          let prod_brand = $.trim($(this).find('meta[itemprop="name"]').attr('content')).replace('\n','');
          let prod_category = $.trim($(this).find('h3.getProductCollection').html()).replace('\n','');
          let prod_variant = '';
          if($.trim(prod_id) !== '' && prod_name !== ''){
                let new_item = {
                    'item_id': prod_id,
                    'item_name': prod_name,
                    'price': prod_price,
                    'item_brand': prod_brand,
                    'item_brand': prod_category,
                    'item_variant': prod_variant,
                    'item_list_name': (nome_pagina == 'search' ? 'Search Results' : 'Category')
                };
                products.push(new_item);
            }
          
        });

        //console.log(products);

        dataLayer.push({ ecommerce: null });  // Clear the previous ecommerce object.
        dataLayer.push({
            event: "view_item_list",
            ecommerce: {
                items:products
            }
        });


      }

    
    }

  }, 1000);
})
