#!/usr/bin/perl
# ----------------------------------------------------------------------------
# This software is Copyright (C) 2007, All Rights Reserved
# ----------------------------------------------------------------------------
# This program is protected by local and international copyright laws. Any
# use of this program is subject to the the terms of the license agreement
# included as part of this distribution archive. Any other uses are strictly
# prohibited without the written permission of the Vendor and all
# other rights are reserved.
# -----------------------------------------------------------------------------
# Warning : Modifying this program violates your license agreement!
# -----------------------------------------------------------------------------

package IT::ArtMan::CustomMenus::Publish::ArticlePages;

# load modules
use strict;

use IT::Globals;

use vars qw($STH);  # Statement handler

# ------------------------------------------------------------------------------
# Function    : publish
# Description :
# Usage       : &IT::ArtMan::CustomMenus::Publish::ArticlePages::publish();
# ------------------------------------------------------------------------------

sub publish {
  my $rule               = shift || die "no rule specified!\n";
  my $publishUpdatedOnly = shift;
  my $stepRef            = shift || die "no currentStepRef defined!\n";
#  my $subStepRef         = shift || die "no currentSubStepRef defined!\n";

  ### create DB statement handler
  unless ($STH) {
    my $tableName  = "${TABLE_PREFIX}article",
    my $whereQuery = &_createWhereQuery($rule, $publishUpdatedOnly);
    my $sortBy     = &IT::DB::Schema::getTableAttributes($tableName, 'defaultSort') || ['num'];
    foreach (@$sortBy) { # add table prefixes
      if (m/^-?article\./) { next; }
      s/^(-)/${1}article./;
    }

    $STH = &IT::DB::select2({
      'tableNames' => $tableName,
      'where'      => $whereQuery,
      'sortBy'     => $sortBy,
      'limit'      => [$$stepRef, 1_000_000_000], # use one billion to represent infinity so we get all results
    });
  }

  # get next record
  my $record = $STH->fetchrow_hashref('NO_FIELDNAME_PREFIXES');

  # on first step
  my $isFirstStep   = ($$stepRef == 0);
  my $noMoreRecords = !$record;
  if ($isFirstStep) {
    if    ($noMoreRecords && $publishUpdatedOnly) { &IT::MultiStepOperations::addStatusMessage("No Updates for: $rule->{'name'} ($rule->{'type'})\n"); }
    elsif ($noMoreRecords)                        { &IT::MultiStepOperations::addStatusMessage("No articles to publish!\n"); }
    else                                          { &IT::MultiStepOperations::addStatusMessage("Publishing: $rule->{'name'} ($rule->{'type'})\n"); }
  }

  # on last step
  if ($noMoreRecords) {
    $STH = undef; # close statement handler
    return 1;     # stage is complete
  }

  ### publish record
  my $categoryRecords = &IT::ArtMan::CustomMenus::Category::getHashOfCategoryRecords();
  my $currentArticle  = $record;
  my $currentCategory = $categoryRecords->{ $currentArticle->{'categoryNum'} } || {};
  my $isPublished     = ($currentCategory->{'type'} ne 'disabled' && $currentArticle->{'status'} eq 'visible');

  if ($isPublished) {     # publish regular articles
    &IT::MultiStepOperations::addStatusMessage(" - Article: $currentArticle->{'title'}\n");
    my $html     = &getHtmlForArticle($rule, $currentArticle);
    my $filepath = &IT::ArtMan::CustomMenus::Publish::getFilePathAndCreateDirFor($rule, $currentCategory, $currentArticle);
    &IT::File::writeFileFast($filepath, $html);
  }

  # update steps counter
  $$stepRef++;

  # return 0 for stage not complete - return 1 is above when there are no more records
  return 0;
}

# ------------------------------------------------------------------------------
# Function    : _createWhereQuery
# Description : Create a where query to match all applicable articles for this
#               publish rule.
# Usage       : my $where = &_createWhereQuery($rule, $publishUpdatedOnly);
# ------------------------------------------------------------------------------

sub _createWhereQuery {
  if (@_ != 2) { die "_createWhereQuery requires exactly two arguments!\n"; }
  my $rule               = shift || die "no rule specified!\n";
  my $publishUpdatedOnly = shift;

  ### create where query
  my $whereQuery = "article.status = 'visible'";
  $whereQuery   .= " AND article.needsPublish = '1'" if ($publishUpdatedOnly && !$rule->{'alwaysPublish'});

  # filter by category
  if ($rule->{'useCategoryFilter'}) {
    my $categoryNums           = &IT::ArtMan::CustomMenus::Admin::PublishRules::getSelectedCategoryNumsForPublishRule($rule);
    my $categoryWhere          = &IT::ArtMan::CustomMenus::Publish::getWhereForFilteringByCategoryField($categoryNums);
    $whereQuery               .= " AND ($categoryWhere)" if $categoryWhere;
  }

  # filter by publish rule conditionals
  if ($rule->{'useRecordFilter'}) {
    my $whereConditionals = &IT::ArtMan::CustomMenus::Publish::getWhereForPublishRuleConditionFilter($rule);
    $whereQuery .= " AND ($whereConditionals)" if $whereConditionals;
  }

  #
  return $whereQuery;
}

# ------------------------------------------------------------------------------
# Function    : getHtmlForArticle
# Description :
# Usage       : my $html = &IT::ArtMan::CustomMenus::Publish::ArticlePages::getHtmlForArticle($rule, $articleRecord);
# ------------------------------------------------------------------------------

sub getHtmlForArticle {
  if (@_ != 2) { die "getHtmlForArticle requires 2 arguments!"; }
  my $rule            = shift || die "no rule specified!";
  my $currentArticle  = shift || die "no article records specified";

  # get current category
  my $categoryRecords = &IT::ArtMan::CustomMenus::Category::getHashOfCategoryRecords();
  my $currentCategory = $categoryRecords->{ $currentArticle->{'categoryNum'} } || {};

  # generate page content
  my $placeholders = &IT::ArtMan::CustomMenus::Publish::createPlaceholders($currentCategory, $currentArticle, $rule->{'template'}, $rule->{'num'});
  my $html         = &template($rule->{'template'}, $placeholders);
  return $html;
}

# ----------------------------------------------------------------------------
# end of file
1;

