#    This file is part of WAB, Welcome-a-bit for Wikinews.
#
#    WAB is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    WAB is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Foobar.  If not, see <https://www.gnu.org/licenses/>.

use strict;
use warnings;

use MediaWiki::API;
use LWP::Simple;

use Data::Dumper;
use String::Util qw(trim);
use DateTime::Format::Strptime;
use URI::Escape;
use DateTime::Format::Human;

my $mw = MediaWiki::API->new();
my $wikiURL = 'https://en.wikinews.org'; # /w/api.php';
$mw->{config}->{api_url} = "$wikiURL/w/api.php";

# input: 		{
#		list => $list, 
#		username => $username,
#		dType => $hf->{deliveryType}
#	};
sub _deliver{
    my $hr = shift;
    
}

sub parseTsFromCatMembers{
	my $ts = shift;
	    my $strp = DateTime::Format::Strptime->new(
        pattern => '%FT%H:%M:%SZ',
        time_zone => 'local',
    );
    my $dt = $strp->parse_datetime($ts);
    return $dt->epoch;
}

# Notify the user of new messages
sub _notify_user{
    my $hr = shift; #hash ref
    
    my $username = $hr->{username};
    
    my $cat = $hr->{cat};
    print "... [$cat]: Notifying $username of new entries...\r\n";
    my $category_one_entry_ref = $mw->api ( {
        action  => 'query',
        list    => 'categorymembers',
        cmtitle => "Category:$cat",
        cmprop  => 'timestamp|title',
        cmsort  => 'timestamp',
        cmdir   => 'desc',
        cmlimit => 100
    });
    my $array = $category_one_entry_ref->{query}->{categorymembers};
    my $list = '';
    for my $entry (@$array){
		my $tsEpoch = parseTsFromCatMembers($entry->{timestamp});
		if($tsEpoch <= $hr->{userTs}){
			last;
		}
		print "... ... Title: '";
		my $title = $entry->{title};
		my $url = "$wikiURL/wiki/$title";
		$url = uri_escape($url);
		
		my $dt = DateTime->from_epoch( epoch => $tsEpoch);
		my $dt1 = $dt->ymd;
		my $dt2 = $dt->hms;
		
		
		$list += "$title (added on $dt1 $dt2)\r\n $url\r\n";
	};
	print Dumper $list;
	_deliver({
		list => $list, 
		username => $username,
		dType => $hr->{deliveryType}
	});
    
    
}

# Check for new messages for $hr = {
#		        'cat' => $cat,
#		        'username' => $username,
#		        'title' => $title    
#	        };
sub _my_process_cat{
    my $hr = shift; #hash ref
    
    # Get the timestamp of the latest entry in the category
    # https://www.mediawiki.org/wiki/API:Categorymembers    
    
    my $cat = $hr->{cat};
    print Dumper $cat;
    my $category_one_entry_ref = $mw->api ( {
        action  => 'query',
        list    => 'categorymembers',
        cmtitle => "Category:$cat",
        cmprop  => 'timestamp|title',
        cmsort  => 'timestamp',
        cmdir   => 'desc',
        cmlimit => 0
    });
    
    # Get the timestamp of the latest entry delivered to the user
    # 2019-02-07T15:50:55Z
    my $ts = $category_one_entry_ref->{query}->{categorymembers}->[0]->{timestamp};
    my $tsEpoch = parseTsFromCatMembers($ts);
    print "..\r\n";
    
    # Compare the time stamps
    my $userTs = $hr->{userTs};
    
    # A fresh message is available
    print "... $cat - checking for time stamps! \r\n";
    if($userTs < $tsEpoch){
		print "need to notify user! their time stamp is outdated!";
		_notify_user($hr);
	}
}

# get category members of 'Gryllida/WAB'
my $members_ref = $mw->api ( {
    action      => 'query',
    list => 'categorymembers',
    cmtitle => 'Category:Gryllida/WAB' 
});
my $members = $members_ref->{query}->{categorymembers};
my $n = scalar(@{$members});

# For each WAB tracking page, extract the username and categories therein.
for (my $i=0; $i < $n; $i++) {
    my $title = $members->[$i]->{title};
    my @partsOfTitle = split /\//, $title;
    $partsOfTitle[0] =~ s/User\://;
    my $username =$partsOfTitle[0];
    my $typeOfArticles =$partsOfTitle[2]; # dev or pub
    my $deliveryType =$partsOfTitle[3]; # email or wiki
    # Get the user's time stamp
    my $url2 = "$wikiURL/wiki/User talk:$username/wab/$typeOfArticles/$deliveryType?action=raw";
    my $content2 = get($url2);
    my @lines2 =  split /^/, $content2;
    my $userTs = $lines2[0];
    print $userTs;
    # Get list of categories of the user
    my $url = "$wikiURL/wiki/$title?action=raw";
    my $content = get($url);
    my @lines =  split /^/, $content;
    
    for my $line (@lines){
	    chomp($line);
	    if ($line =~ s/\*(.*)/$1/){
	        my $cat = trim($line);
	        # For this username and category, check for new messages.
	        _my_process_cat({
		        'cat' => $cat,
		        'username' => $username,
		        'title' => $title,
		        'userTs' => $userTs,
		        'deliveryType' => $deliveryType,
		        'articleType' => $typeOfArticles
	        });
	    }
    }
}
