#!usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
use JSON::XS qw(encode_json decode_json);
use File::Slurp qw(read_file write_file);
use Getopt::Long qw(GetOptions);
use File::Basename;
use HTTP::Cookies;
use Cwd qw(cwd);

my %config = (
    'profile' => undef,
    'SRCRoot'  => './src/',
    'uploadPHP_CMD' => '/usr/bin/php ./vendor/mgp25/instagram-php/examples/uploadPhoto.php',
    'uploadPHP_debug' => 1,
    'uploadPHP_truncated_debug' => 1,
    'uploadPHP_autoload' => cwd . '/src/mpg25-instagram-api/vendor/autoload.php',
);

my %profile = (
    'dreamyourmansion' => {
                            'DBFilepath' => './src/db/db_dreamyourmansion.dat',
                            'imageDir' => './src/images/dreamyourmansion',
                            'filename_as_title' => 0,
                            'uploadPHP' => {
                                            'username' => 'dreamyourmansion',
                                            'password' => 'nBLT!4H3aI@c',
                                            'truncated_debug' => 1,
                                            'proxy_user' => 'zino%40onlinehome.de',
                                            'proxy_password' => 'zinomedial33t',
                                            'proxy_ip' => 'de786.nordvpn.com',
                                            'proxy_port' => 80,
                                            'tags' => '#investment #immobilie #mansionhouse #dream #poolhouse #villa #realestate #loft #awesome #lifestyle #motivation #luxury',
                                            'description_add' => "The most beautiful real estates in the world!",
                            },
    },
    'vstbestprices' => {
                            'DBFilepath' => './src/db/db_vstbestprices.dat',
                            'imageDir' => './src/images/vstbestprices',
                            'filename_as_title' => 1,
                            'uploadPHP' => {
                                            'username' => 'vstbestprices',
                                            'password' => 'Vst#1337vst#1337',
                                            'truncated_debug' => 1,
                                            'proxy_user' => 'zino%40onlinehome.de',
                                            'proxy_password' => 'zinomedial33t',
                                            'proxy_ip' => 'de435.nordvpn.com',
                                            'proxy_port' => 80,
                                            'tags' => '#Beats #FLStudio20 #Producer #Ableton #Beatmaker #Studio #ProTools #Music #DAW #LogicPro #FruityLoops #VST #VSTplugins #NativeInstruments #MIDI #Drums #AutoTune #Spectrasonics #Omnisphere #AutoTune #Plugins #Keyscape #Trilian #Logic',
                                            'description_add' => 'INSTALLATION SUPPORT is included in all prices so you can relax and focus on producing!',
                            },
    },
    'vstbestprices_testing' => {
                            'DBFilepath' => './src/db/db_vstbestprices.dat',
                            'imageDir' => './src/images/vstbestprices',
                            'filename_as_title' => 1,
                            'uploadPHP' => {
                                            'username' => 'adobebestprices',
                                            'password' => 'vst#1337',
                                            'truncated_debug' => 1,
                                            'proxy_user' => 'zino%40onlinehome.de',
                                            'proxy_password' => 'zinomedial33t',
                                            'proxy_ip' => 'de435.nordvpn.com',
                                            'proxy_port' => 80,
                                            'tags' => '#Beats #FLStudio20 #Producer #Ableton #Beatmaker #Studio #ProTools #Music #DAW #LogicPro #FruityLoops #VST #VSTplugins #NativeInstruments #MIDI #Drums #AutoTune #Spectrasonics #Omnisphere #AutoTune #Plugins #Keyscape #Trilian #Logic',
                                            'description_add' => 'INSTALLATION SUPPORT is included in all prices so you can relax and focus on producing!',
                            },
    },
    'adobebestprices' => {
                            'DBFilepath' => './src/db/db_adobebestprices.dat',
                            'imageDir' => './src/images/adobebestprices/',
                            'filename_as_title' => 0,
                            'uploadPHP' => {
                                            'username' => 'adobebestprices',
                                            'password' => 'vst#1337',
                                            'truncated_debug' => 1,
                                            'proxy_user' => 'zino%40onlinehome.de',
                                            'proxy_password' => 'zinomedial33t',
                                            'proxy_ip' => 'de435.nordvpn.com',
                                            'proxy_port' => 80,
                                            'tags' => '#adobe #photoshop #adobeillustrator #vector #illustrator #adobephotoshop #vectorart #graphicdesign #aftereffects #logo #cs6 #lightroom #graphic',
                                            'description_add' => 'Photoshop, Lightroom, Illustrator, Dreamviewer, Premiere for WIN & MAC | Installation support is included in all our prices!',
                            },
    },
);

my (%data, %db);
my $dbKeysStart = 0;
my $profile;

# MAIN
&CheckParameter();
&UndumpFromFile();
#print Dumper \%db;
&DirectoryListing();
print Dumper \%data;
&FindNewDataset();
&Summary();

sub CheckParameter {
    &Delimiter((caller(0))[3]);
    
    GetOptions ('profile=s' => \$config{'profile'}) or die &PrintUsage();
    die &PrintUsage() if !$config{'profile'};
    $profile = $config{'profile'};
    if (!exists $profile{$profile}) {
        print "Profile '$profile' does not exist.\n";
        &PrintUsage();
        die;
    }
}

sub PrintUsage {
        print "Usage: $0 --profile *name*\n";
        print "Following profiles are available:\n";
        print "* '$_'\n" for keys(%profile);
}

sub UndumpFromFile {
    &Delimiter((caller(0))[3]);
    
    if (-e $profile{$profile}{'DBFilepath'}) {
        my $json = read_file($profile{$profile}{'DBFilepath'}, { binmode => ':raw' });
        if (!$json) {
            warn "DB file $profile{$profile}{'DBFilepath'} is empty.\n";
            return;
        }
        %db = %{ decode_json $json };
        $dbKeysStart = scalar(keys(%db));
        print "INFO: $profile{$profile}{'DBFilepath'} has " . $dbKeysStart . " keys.\n";
    }
    elsif (!-e $profile{$profile}{'DBFilepath'}) {
        print "INFO: NO DB file found at $profile{$profile}{'DBFilepath'}. Creating now... ";
        write_file($profile{$profile}{'DBFilepath'}, '');
        print "done.\n";
        die "Please restart.";
        # &UndumpFromFile();
        
    }
}

sub DirectoryListing {
    &Delimiter((caller(0))[3]);
    
    # opendir(DIR, $profile{$profile}{'imageDir'});
    # my @files = grep(/\.jpg$|\.png$|\.jpeg$|/,readdir(DIR));
    # closedir(DIR);
    my @files = glob ( "$profile{$profile}{'imageDir'}/*" );
    %data = map { $_ => { 'FILEPATH' => "$_" } } @files;
}

sub Summary {
    &Delimiter((caller(0))[3]);
    
    print "$profile{$profile}{'DBFilepath'} has " . scalar(keys(%db)) . " keys (before $dbKeysStart).\n";
}

sub FindNewDataset {
    &Delimiter((caller(0))[3]);
    
    my $i = 0;
    for my $key (keys %data) {
        if (exists $db{$key}) {
            print "OLD: $key\n";
        }
        elsif (!exists $db{$key}) {
            print "NEW: $key\n";
            
            my $success = &uploadPHP($data{$key}{'FILEPATH'});
            &AddToDB($key);
            &WipeData($key);
            last;
            # if ($success) {
            #     print "success is $success\n";
            #     &AddToDB($key);
            #     &WipeData($key);
            #     last;
            # }
        }
        $i++;
    }

    if ($i == scalar(keys(%data))) {
        warn "\nNO NEW FILES AVAILABLE.\n";
    }
}

sub uploadPHP {
    &Delimiter((caller(0))[3]);
    my $filepath = shift;
    
    my $success = 1;
    my $captionText = "$profile{$profile}{'uploadPHP'}{'description_add'}\n\n$profile{$profile}{'uploadPHP'}{'tags'}";
    if ($profile{$profile}{'filename_as_title'}) {
        my $filename = basename($filepath);
        $filename =~ s/(NO INSTALL)|(SymLink Installer)//g;
        $filename =~ s/( , )|(\.[^.]+$)//g;
        $captionText = "$filename\n\n" . $captionText;
        # print Dumper $captionText;
    }
    open PHPOUT, "$config{'uploadPHP_CMD'} \'$filepath\' \'$captionText\' $profile{$profile}{'uploadPHP'}{'username'} $profile{$profile}{'uploadPHP'}{'password'} $config{'uploadPHP_debug'} $config{'uploadPHP_truncated_debug'} $profile{$profile}{'uploadPHP'}{'proxy_user'} $profile{$profile}{'uploadPHP'}{'proxy_password'} $profile{$profile}{'uploadPHP'}{'proxy_ip'} $profile{$profile}{'uploadPHP'}{'proxy_port'} \'$config{'uploadPHP_autoload'}\'|";
    while (<PHPOUT>) {
      print $_; # PRINT CURRENT PHP OUPUT LINE
      if ($_ =~ m/error/) {
          $success = 0;
      }
    }
    
    return $success;
}

sub WipeData {
    &Delimiter((caller(0))[3]);
    my $key = shift;
    
    print "Deleting $data{$key}{'FILEPATH'}...";
    unlink($data{$key}{'FILEPATH'}) or die "Could not delete $data{$key}{'FILEPATH'}!\n";
    print " Done.\n";
}

sub AddToDB {
    &Delimiter((caller(0))[3]);
    my $key = shift;
    
    $data{$key}{'TIMESTAMP_UPLOADED'} = &GetTimestamp('YMDHMS');
    $db{$key} = $data{$key};
    my $json = encode_json \%db;
    write_file($profile{$profile}{'DBFilepath'}, { binmode => ':raw' }, $json);
}

sub Delimiter {
    my $SubName = shift;
    print "\n" . "-" x 80 . "\nSUB " . $SubName . "\n" . '-' x 80 . "\n";
}

sub GetTimestamp {
    #&Delimiter((caller(0))[3]);
	my $switch = shift;
	
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime(time);
    
    my $nice_timestamp;
    if ($switch eq 'YMDHMS') {
    	$nice_timestamp = sprintf ( "%04d%02d%02d_%02d%02d%02d", $year+1900,$mon+1,$mday,$hour,$min,$sec);
    }
    elsif ($switch eq 'YMD') {
    	$nice_timestamp = sprintf ( "%04d%02d%02d", $year+1900,$mon+1,$mday);
    }
    elsif ($switch eq 'year') {
    	$nice_timestamp = $year+1900;
    }
    elsif ($switch eq 'month') {
    	$nice_timestamp = $mon+10;
    }
    else {
    	print "Invalid/no switch detected. Use: 'YMDHMS' / 'YMD'\n";
    }
    
    return $nice_timestamp;
}