<?php

namespace App\Console\Commands\Network;

use App\Console\Commands\BaseCommand;
use App\Models\GeoIp\PrefixGeoIp;
use Illuminate\Support\Facades\Storage;

use Meema\CloudFront\Facades\CloudFront;

use Log;

class GeoIpExport extends BaseCommand
{

    protected $signature = 'geoip:export';

    protected $description = 'Creates CSV suitable for exportation to geo IP providers.';

    protected $notEnterprise = true;

    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(config('creatia.constant.chunk_large'), function($x) use(&$csv_rows) {
                foreach($x as $y) {

                    switch($y->region) {
                        case 'CN-MO': $y->country = 'MO'; $y->region = null; break;
                        case 'CN-HK': $y->country = 'HK'; $y->region = null; break;
                        case 'GU-GU': $y->country = 'GU'; $y->region = null; break;
                        case 'IM-IM': $y->country = 'IM'; $y->region = null; break;
                        case 'HK-HCW': $y->country = 'HK'; $y->region = null; break;
                        case 'PR-PR': $y->country = 'PR'; $y->region = null; break;
                        case 'DO-DN': $y->country = 'DO'; $y->region = 'DO-01'; break;
                        case 'BM-BM': $y->country = 'BM'; $y->region = null; break;
                        case 'KY-KY': $y->country = 'KY'; $y->region = null; break;
                        case 'FR-75': $y->country = 'FR'; $y->region = 'FR-IDF'; break;
                        case 'CU-02': $y->country = 'CU'; $y->region = 'CU-03'; break;
                        case 'MA-RBA': $y->country = 'MA'; $y->region = 'MA-RAB'; break;
                        case 'PL-WA': $y->country = 'PL'; $y->region = 'PL-14'; break;
                        case 'FI-ES': $y->country = 'FI'; $y->region = 'FI-18'; break;
                        case 'JE-JE': $y->country = 'JE'; $y->region = null; break;
                    }

                    $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)) {
                \Log::debug("We would push the Geo IP feed...");
            }

            if(hash('sha512', $file) != hash('sha512', $final_content) && config('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,
                    [
                        'ContentType'  => 'text/csv; charset=utf-8',
                        'CacheControl' => 'max-age=86400',
                    ]
                );
                CloudFront::invalidate(['/google-data/GSL-geoip-feed.csv'], config('cloudfront.distribution_id'));
            }
        }
        
        return 0;
    }
}