# ==================================================================
# Plugins::Widgets - Auto Generated Program Module
#
#   Plugins::Widgets
#   Author  : Bao Phan
#   Version : 1.0
#   Updated : Mon Mar 21 11:08:31 2016
#
# ==================================================================
#

package Plugins::Widgets;
# ==================================================================

use strict;
use GT::Base;
use GT::Plugins qw/STOP CONTINUE/;
use Links qw/:objects/;

# Inherit from base class for debug and error methods
@Plugins::Widgets::ISA = qw(GT::Base);

# Your code begins here.


# ADMIN MENU OPTIONS
# ===================================================================

sub widgets {
# -------------------------------------------------------------------
# This subroutine will be called whenever the user clicks on 'Widgets' in the
# admin menu.  Remember, you need to print your own HTTP header; to do so you
# can use:
    my $args = shift || {};

    print $IN->header;
    Links::admin_page('widgets.html', { widgets => fetch_widgets($IN->param('page')), %$args });
}

sub assign {
    my $cgi = $IN->get_hash();

    my $msg;
    if ($cgi->{page} and $cgi->{id} and $cgi->{pos}) {
        my $widget = $DB->table('Widgets')->get($cgi->{id});
        my $page   = $cgi->{page};

        my $tab_pgwidgets = $DB->table('PageWidgets');
        my $pg_widget = $tab_pgwidgets->select({ WidgetID => $widget->{ID}, Page => $page })->fetchrow_hashref;

        my ($msg, $category);

        $category = $DB->table('Category')->get($page) if $page =~ /^\d+$/;
        if (!$pg_widget and $cgi->{pos} =~ /^\d+$/) {
            $tab_pgwidgets->insert({ WidgetID => $widget->{ID}, Page => $page, Sort_Pos => $cgi->{pos} || 0 }) or die $GT::SQL::error;
            $msg = "The widget was added to page: " . ($category ? $category->{Full_Name} : $page);
        }
        elsif ($cgi->{pos} =~ /^\d+$/) {
            $tab_pgwidgets->update({ Sort_Pos => $cgi->{pos} }, { ID => $pg_widget->{ID} });
            $msg = "The widget's position was updated on page: " . ($category ? $category->{Full_Name} : $page);
        }
        else {
            $tab_pgwidgets->delete({ ID => $pg_widget->{ID} });
            $msg = "The widget was removed from: " . ($category ? $category->{Full_Name} : $page);
        }
    }
    return widgets({ msg => $msg });
}

sub add {
    my $cgi = $IN->get_hash();

    my $error;
    if ($cgi->{submit}) {
        # automated widget
        my @fields = ('ID', 'Type', 'Widget', 'Title', 'Subtitle', 'TitleStyle', 'Image', 'URL', 'Button');
        if ($cgi->{Type}) {
            return form('Widget and Title cannot be null') unless $cgi->{Widget} and $cgi->{Title};

            if ($cgi->{Widget} eq 'category_list') {
                return form('Select a category') unless $cgi->{Category};

                push @fields, 'Category';
            }
            elsif ($cgi->{Widget} eq 'poll') {
                return form('Select a forum') unless $cgi->{Forum};

                push @fields, 'Forum';
            }
            elsif ($cgi->{Widget} =~ /^(:?feature_article|editors_pick|feature_threads)$/) {
                return form('Enter Article IDs, comma separated') unless $cgi->{Articles};
                push @fields, 'Articles';
            }
            elsif ($cgi->{Widget} eq 'newsletter') {
                return form('Enter List ID') unless $cgi->{ListID};
                push @fields, 'ListID';
            }
            elsif ($cgi->{Widget} eq 'external') {
                return form('Enter widget title') unless $cgi->{Title};
            }
        }


        my $rec;
        if ($cgi->{Widget} eq 'external') {
            $rec = $DB->table('Widgets')->add({
                Title           => $cgi->{Title},
                TitleStyle      => $cgi->{TitleStyle},
                Widget          => 'external',
                Type            => 1
            });
            return form($GT::SQL::error) unless $rec;

            my $num_links = $cgi->{NumLinks} || 5;
            my $tab_links = $DB->table("WidgetLinks");
            for my $i (1 .. $num_links) {
                next unless $cgi->{"Title-$i"} and $cgi->{"Abstract-$i"} and $cgi->{"URL-$i"} and $cgi->{"URL-$i"} =~ /^http/;
                $tab_links->insert({
                    WidgetID    => $rec,
                    Title       => $cgi->{"Title-$i"},
                    Abstract    => $cgi->{"Abstract-$i"},
                    URL         => $cgi->{"URL-$i"},
                });
            }
        }
        else {
            my %hash = map { $_ => $cgi->{$_} } @fields;
            $rec = $DB->table('Widgets')->add(\%hash);
            return form($GT::SQL::error) unless $rec;
        }


        if ($cgi->{page}) {
            my $tab_pgwidgets = $DB->table('PageWidgets');
            my $max_pos = $tab_pgwidgets->select('MAX(Sort_Pos)', { Page => $cgi->{page} })->fetchrow || 0;
            $tab_pgwidgets->insert({ WidgetID => $rec, Page => $cgi->{page}, Sort_Pos => $max_pos + 1 });
        }
        return widgets({ success => "The widget was added" });
    }

    form();
}

sub modify {
    my $cgi    = $IN->get_hash();
    my $widget = $DB->table('Widgets')->get($cgi->{ID});
    return form("Widget not found") unless $widget;

    if ($cgi->{submit}) {
        # automated widget
        my @fields = ('ID', 'Type', 'Widget', 'Title', 'Subtitle', 'TitleStyle', 'Image', 'URL', 'Button');
        if ($cgi->{Type}) {
            return form('Widget and Title cannot be null') unless $cgi->{Widget} and $cgi->{Title};

            if ($cgi->{Widget} eq 'category_list') {
                return form('Select a category') unless $cgi->{Category};
                push @fields, 'Category';
            }
            elsif ($cgi->{Widget} eq 'poll') {
                return form('Select a forum') unless $cgi->{Forum};
                push @fields, 'Forum';
            }
            elsif ($cgi->{Widget} =~ /^(:?feature_article|editors_pick|feature_threads)$/) {
                return form('Enter Article IDs, comma separated') unless $cgi->{Articles};
                push @fields, 'Articles';
            }
            elsif ($cgi->{Widget} eq 'newsletter') {
                return form('Enter List ID') unless $cgi->{ListID};
                push @fields, 'ListID';
            }
            elsif ($cgi->{Widget} eq 'external') {
                return form('Enter widget title') unless $cgi->{Title};
            }
        }

        my %hash  = map { $_ => $cgi->{$_} } @fields;
        if ($cgi->{Widget} eq 'external') {
            $DB->table('Widgets')->update({
                Title           => $cgi->{Title},
                TitleStyle      => $cgi->{TitleStyle},
            }, { ID => $cgi->{ID} });

            my $num_links = $cgi->{NumLinks} || 5;
            my $tab_links = $DB->table("WidgetLinks");
            for my $i (1 .. $num_links) {
                my $id = $cgi->{"ID-$i"};
                
                unless ($cgi->{"Title-$i"} and $cgi->{"URL-$i"} and $cgi->{"URL-$i"} =~ /^http/) {
                    $tab_links->delete({ ID => $id }) if $id;
                }
                elsif ($id) {
                    $tab_links->update({
                        Title       => $cgi->{"Title-$i"},
                        Abstract    => $cgi->{"Abstract-$i"},
                        URL         => $cgi->{"URL-$i"},
                    }, { ID => $id });
                }
                else {
                    $tab_links->insert({
                        WidgetID    => $cgi->{ID},
                        Title       => $cgi->{"Title-$i"},
                        Abstract    => $cgi->{"Abstract-$i"},
                        URL         => $cgi->{"URL-$i"},
                    });
                }
            }
        }
        else {
            my $rec = $DB->table('Widgets')->modify(\%hash);
        }
        return widgets({ success => "The widget was updated" });
    }
    else {
        $IN->param($_, $widget->{$_}) for keys %$widget;
        if ($widget->{Widget} eq 'external') {
            my $links = $DB->table('WidgetLinks')->select({ WidgetID => $widget->{ID} })->fetchall_hashref;
            my $i = 1;
            foreach my $l (@$links) {
                $IN->param("$_-$i", $l->{$_}) foreach (qw/ID Title Abstract URL/);
                $i++;
            }
        }
        return form();
    }
}

sub retrieve_ntag {
    my ($name, $index) = @_;
    return unless $name and $index;
    my $vars = GT::Template->vars;

    return $vars->{"$name-$index"};
}

sub delete {
    my $tab    = $DB->table('Widgets');
    my $widget = $tab->get($IN->param('ID'));
    return widgets({ error => "Widget not found" }) unless $widget;

    $tab->delete({ ID => $widget->{ID} });
    $DB->table('PageWidgets')->delete({ WidgetID => $widget->{ID} });
    $DB->table('WidgetLinks')->delete({ WidgetID => $widget->{ID} });
    widgets({ success => "The widget was deleted" });
}

sub form {
    print $IN->header;
    my $widget = $IN->param('Widget') || '';

    Links::admin_page($widget eq 'external' ? 'widgetlink_add.html' : 'widget_add.html', { error => shift });
}

sub fetch_widgets {
    my $page = shift;

    my $tab = $DB->table('Widgets');
    my $tab_pgwidgets = $DB->table('PageWidgets');
    my $tab_category  = $DB->table('Category');

    $tab->select_options('ORDER BY Title');
    my $widgets = $tab->select()->fetchall_hashref;

    my (%selected, %widgets);
    if ($page) {
        %selected = map { $_->{WidgetID} => $_->{Sort_Pos} } @{$tab_pgwidgets->select({ Page => $page })->fetchall_hashref};
    }

    my (@selected, @noselected);
    foreach my $w (@$widgets) {
        if ($w->{Image}) {
            my $fh = $tab->file_info('Image', $w->{ID});
            $w->{Image_URL} = '/images/widgets/' . $fh->File_RelativeURL;
        }

        $w->{pages} = $tab_pgwidgets->select({ WidgetID => $w->{ID} })->fetchall_hashref;
        if ($selected{$w->{ID}}) {
            $w->{selected} = $selected{$w->{ID}};
            push @selected, $w;
        }
        else {
            push @noselected, $w;
        }
    }

    @selected = @{qsort(\@selected, 'selected', 'asc')} if scalar @selected;
    return { selected => \@selected, available => \@noselected };
}

sub fetch_categories {
    my $tab = $DB->table('Category');

    $tab->select_options('ORDER BY Full_Name');
    my $categories = $tab->select()->fetchall_hashref;
    return $categories;
}

sub qsort {
    my ($list, $sb, $so)  = @_;
    my $sorted;
    @$sorted =
    sort {
        my $da = lc $a->{$sb};         #lower case
        my $db = lc $b->{$sb};
        my $res;
        if ($sb eq 'selected') {
            $res = $db <=> $da;
        }
        else {
            $res = $db cmp $da;
        }
        if ($res == 0 and $sb ne 'name') {
            lc $b->{name} cmp lc $a->{name};
        }
        else {
            $res;
        }
    } @$list;

    ($so) and @$sorted = reverse @$sorted;
    return $sorted;
}
1;
