<?php

namespace App\Modules\Network\Commands;

use App\Modules\Network\Models\GeoIp\PrefixGeoIp;
use Illuminate\Support\Facades\Storage;

use Meema\CloudFront\Facades\CloudFront;
use Meema\CloudFront\Jobs\InvalidateCache;

use Log;

class GeoIpExport extends \App\Console\Commands\BaseCommand
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'geoip:export';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Creates CSV suitable for exportation to geo IP providers.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $csv_rows = [];
        PrefixGeoIp::leftJoin('prefixes', 'prefixes.id', '=', 'prefix_id')->select('address', 'mask', 'country', 'region', 'city')
            ->whereNull('prefixes.deleted_at')
            ->whereNotNull('country')
            ->whereNotNull('region')
            ->whereNotNull('city')
            ->orderBy('address')
            ->orderBy('mask')
            ->chunk(env('CHUNK_SIZE'), function($x) use(&$csv_rows) {
                foreach($x as $y) {
                    $csv_rows[] = ["$y->address/$y->mask", $y->country ?? '', $y->region ?? '', trim($y->city) ?? ''];
                }
            });

        $output_fh = fopen('php://output', 'w+');

        ob_start();

        foreach($csv_rows as $row) {
            $row[] = '';

            fputs($output_fh, implode(',', $row)."\n");
        }

        $final_content = ob_get_clean();

        fclose($output_fh);

        file_put_contents(storage_path('geo-ip-feed.csv'), $final_content);
        
        if (Storage::disk('s3')->exists('/google-data/GSL-geoip-feed.csv')) {
            $file = Storage::disk('s3')->get('/google-data/GSL-geoip-feed.csv');

            if(hash('sha512', $file) != hash('sha512', $final_content) && env('APP_ENV') != 'development')
            {
                static::notify("Uploading GeoIP feed to handle the latest changes.");
                Storage::disk('s3')->put('/google-data/GSL-geoip-feed.csv', $final_content);
                CloudFront::invalidate(['/google-data/GSL-geoip-feed.csv'], env('AWS_CLOUDFRONT_DISTRIBUTION_ID'));
            }
        }
        
        return 0;
    }
}