#!/usr/bin/perl -w

use strict;
use warnings;
use utf8;
use 5.10.1;

use URI;
use JSON;
use Web::Scraper;
use LWP::Simple;
# use Data::Dump 'pp';
use Data::Dumper;
use Time::HiRes qw(time);

use utf8;
binmode(STDOUT, ":utf8");
binmode(STDIN, ":utf8");


sub _process_unibet {
    my ($node_id) = @_;
    
   # my $url = "https://www.unibet.fr/zones/automaticcoupon/display-markets.json?nodeId=$node_id&type=R\%25C3\%25A9sultat";

	my $url = "https://www.unibet.fr/zones/eventpath/display-markets.json?nodeId=$node_id&type=R%25C3%25A9sultat";

    my $content = get $url;
    die "Couldn't get $url" unless defined $content;
    
    my $data = decode_json($content);
    
    print "DATA:\n";
    # print Dumper $data;

#    foreach my $k (@{$data->{marketsByType}}) {
#    	if ($k->{marketName} eq "'Résultat du matc") {
    		
    		
 #   		}
    
    my $check_time = sprintf("%.3f",time)*1000 + 86400*3;
    
#    foreach my $k (keys %{$data->{marketsByType}->{'Résultat du match'}}) {
	foreach my $k (@{$data->{marketsByType}}) {
		print "$k->{marketName}\n";
		if ($k->{marketName} =~ m/sultat du matc/) {
			print "->>>>\n";
			foreach my $d (@{$k->{days}}) {
				print "D";
				foreach my $match (@{$d->{events}}) {
					print "M";
					print $match->{eventName};
					print "\n";

					next unless $match->{eventName} =~ m/nice/i;
					print "Match: $match->{eventName} \n";

		            my $file_name = "stats/".$match->{'eventId'}.".json";
		            my $file_name_3d = "stats/".$match->{'eventId'}."_3d.json";
		           
		           # Determining file name.
					# This logic seems convoluted, but is left here because I don't know understand
					# the reasoning
		           
		           if (-f $file_name) {
        		        if (-f $file_name_3d) {
                	    	next;
                			}
                		else {
                    		if ( $check_time < $match->{'eventStartDate'}) {
                        		next;
                    			}
                    		else {
                        		$file_name = $file_name_3d;
                    			}
                			}
            			}

            		my $matchcontent = get "https://www.unibet.fr/zones/event.json?eventId=".$match->{'eventId'};
            		print ("Fetching: https://www.unibet.fr/zones/event.json?eventId=" . $match->{'eventId'} . "\n");
            		my $event = decode_json($matchcontent);
            		
            		foreach my $m (@{$event->{marketClassList}}) {
            		#	print Dumper $m;
            		#	print qq!\n--------\n!;
            		# print "Market: $m->{'marketName'}\n";
            		
            		
            		
               		 if ( $m->{'marketName'} eq "Résultat du match" ) {
                    		
                    		# print Dumper $m;
                    		# No idea if this could happen
                    		if (scalar $m->{'marketList'} > 1) { print "MARKET LIST > 1\n"; }
                    		my $id = $m->{'marketList'}[0]->{'betradarId'};
                    		print "Got betradarId: $id\n";
                    		
                    		if ($id) {
                    			my $stats = {};
                    			$stats->{'stats_match_form'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_match_form/".$id;
                         		my $home_team_id = $stats->{'stats_match_form'}{'doc'}[0]{'data'}{'teams'}{'home'}{'team'}{'uid'};
                         		my $away_team_id = $stats->{'stats_match_form'}{'doc'}[0]{'data'}{'teams'}{'away'}{'team'}{'uid'};
                         
                         		$stats->{'home_stats_team_lastx'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_lastx/".$home_team_id;
                         		$stats->{'away_stats_team_lastx'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_lastx/".$away_team_id;

                         		$stats->{'stats_team_versusrecent'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_versusrecent/".$home_team_id."/".$away_team_id;
 
                         		$stats->{'match_info'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/match_info/".$id;
                         		my $season_id = $stats->{'match_info'}{'doc'}[0]{'data'}{'match'}{'_seasonid'};
                         
                         		$stats->{'stats_season_tables'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_season_tables/".$season_id;
                         		$stats->{'stats_formtable'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_formtable/$season_id/1/-1/5";

                         		open my $fh, ">", $file_name;
                         		print $fh encode_json($stats);
                         		close $fh;
                    			
                    			
                    			}
                    		
                    		
                    		
                    		}
						}
					# exit;
				}
			}
		
		exit;

		
#         foreach my $match (@{$data->{marketsByType}->{'Résultat du match'}->{$k}}) {
# 
#             my $check_time = sprintf("%.3f",time)*1000 + 86400*3;
# 
#             my $file_name = "stats/".$match->{'eventId'}.".json";
#             my $file_name_3d = "stats/".$match->{'eventId'}."_3d.json";
#                 
#             #    `touch $file_name`;
#             #    `touch $file_name_3d`;
# 
#             if (-f $file_name) {
#                 if (-f $file_name_3d) {
#                     next;
#                 }
#                 else {
#                     if ( $check_time < $match->{'eventStartDate'}) {
#                         next;
#                     }
#                     else {
#                         $file_name = $file_name_3d;
#                     }
#                 }
#             }
#             
#             
            
#             my $content = get "https://www.unibet.fr/zones/event.json?eventId=".$match->{'eventId'};
#             my $event = decode_json($content);
#             foreach my $m (@{$event->{markets}}) {
#                 if ( $m->{'marketName'} eq 'Résultat du match' ) {
#                     my $id = $m->{'betradarId'};
# 
#                     if ( $id ) {
# 
#                         my $stats = {};
# 
#                         # $stats->{'stats_match_tableslice'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_match_tableslice/".$id;
#                         $stats->{'stats_match_form'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_match_form/".$id;
# 
#                         # say ref $stats->{'stats_match_form'}{'doc'};
# 
#                         my $home_team_id = $stats->{'stats_match_form'}{'doc'}[0]{'data'}{'teams'}{'home'}{'team'}{'uid'};
#                         my $away_team_id = $stats->{'stats_match_form'}{'doc'}[0]{'data'}{'teams'}{'away'}{'team'}{'uid'};
#                         
#                         $stats->{'home_stats_team_lastx'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_lastx/".$home_team_id;
#                         $stats->{'away_stats_team_lastx'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_lastx/".$away_team_id;
#                         
#                         # $stats->{'home_stats_team_nextx'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_nextx/".$home_team_id;
#                         # $stats->{'away_stats_team_nextx'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_nextx/".$away_team_id;
#                         
#                         # $stats->{'home_stats_team_winpercentage'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_winpercentage/".$home_team_id;
#                         # $stats->{'away_stats_team_winpercentage'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_winpercentage/".$away_team_id;
#                         
#                         # $stats->{'home_stats_team_info'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_info/".$home_team_id;
#                         # $stats->{'away_stats_team_info'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_info/".$away_team_id;
# 
#                         $stats->{'stats_team_versusrecent'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_team_versusrecent/".$home_team_id."/".$away_team_id;
# 
#                         $stats->{'match_info'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/match_info/".$id;
#                         my $season_id = $stats->{'match_info'}{'doc'}[0]{'data'}{'match'}{'_seasonid'};
#                         
#                         $stats->{'stats_season_tables'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_season_tables/".$season_id;
#                         
#                         $stats->{'stats_formtable'} = decode_json get "https://ls.sportradar.com/ls/feeds/?/unibetfr/fr/Europe:Berlin/gismo/stats_formtable/$season_id/1/-1/5";
# 
#                         open my $fh, ">", $file_name;
#                         print $fh encode_json($stats);
#                         close $fh;
#                     }
#                 }
#             }
         }
     }

}

sub maj_unibet {
    my $url = 'https://www.unibet.fr/sport/football';
    my $content = get $url;
    die "Couldn't get $url" unless defined $content;
    
    my ($node_id) = ($content =~ /nodeId\s+:\s+(\d+),/s);
    
    _process_unibet($node_id);
}

maj_unibet();
