#  This file is part of KWeather.
#  Copyright (c) 2021 Emanoil Kotsev <deloptes@gmail.com>
#
#  This program 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 2 of the License, or
#  (at your option) any later version.
#
#  This program 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 this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#  As a special exception, permission is given to link this program
#  with any edition of TQt, and distribute the resulting executable,
#  without including the source code for TQt in the source distribution.


use strict;
use warnings;
use utf8;
#use Data::Dumper qw(Dumper);

######## pick arguments

my $stationsNSD  = $ARGV[0]; # data/nsd_cccc.txt
my $stationNames = $ARGV[1]; # data/station_names.txt
my $desktopIn    = $ARGV[2]; # weather_stations.desktop.in

######## generate stations.dat

#input format ICAO;status;location;name;INFO1;INFO2

my %stnames;
open(FDSN, "<", $stationNames) || die "can not open file $!";
while (<FDSN>) {
	my $line = $_; chomp $line;
	my ($key,$status,$loc,$name,$v1,$v2) = split(/;/,$line);
	$status = '' if $status =~ /none|false|na|decomissioned/;
	$stnames{$key} = { 'status' => $status,
	                   'loc' => $loc,
	                   'name' => $name,
	                   'v1' => $v1,
	                   'v2' => $v2
	               };
}
close(FDSN);

open(FDNSD, "<", $stationsNSD) || die "can not open file $!";
open(FDOUT, ">", "stations.dat") || die "can not open file $!";
while (<FDNSD>) {
	my $line = $_; chomp $line;
	my @entries = split(/;/,$line,6);
	if ( exists $stnames{$entries[0]} ) {
		next if ! exists $stnames{$entries[0]}{'status'};
		$entries[3] = $stnames{$entries[0]}{'name'};
	}
	print FDOUT join(';', @entries) , "\n";
#	print join(';', @entries) , "\n" ;
}
close(FDOUT);
close(FDNSD);

#print Dumper \%stnames and exit;

######## generate weather_stations.desktop

my $section;
my %data;

## parse weather_stations.desktop.in

open(FDWSTIN, "<", $desktopIn) || die "can not open file $!";
while (my $line = <FDWSTIN>) {
    if ($line =~ /^\s*#/) {
        next;        # skip comments
    }
    if ($line =~ /^\s*$/) {
        next;    # skip empty lines
    }
    if ($line =~ /^\[(.*)\]\s*$/) {
        $section = $1;
        next;
    }

    if ($line =~ /^([^=]+?)\s*=\s*(.*?)\s*$/) {
        my ($field, $value) = ($1, $2);
        if (not defined $section) {
            warn "Line outside of seciton '$line'\n";
            next;
        }
        $data{$section}{$field} = $value;
    }
}
close(FDWSTIN);

#print Dumper \%data and exit;

open(FDST, "<", "stations.dat") || die "can not open file $!";
while(<FDST>) {
    my $line = $_; chomp $line;
    my @entries = split(/;/,$line);
    #print Dumper \@entries and exit;
    my $k;
    my $found = 0;
    
    if ( ! exists $stnames{$entries[0]}{'loc'} ) {
        my @regions = split (/\s/, $data{'Main'}{'regions'});
        foreach my $r (@regions) {
            if (!$entries[4]) {
                my @states = split (/\s/, $data{$r}{'states'});
                foreach my $s (@states) {
                    $k = "$r" . "_" . "$s";
                    if ( exists $data{$k}{'name'} 
                        and $data{$k}{'name'} eq $entries[5]) { # state/country matches
                            $found = 1;
                            last;
                    }
                }
            } else {
                $k = "$r" . "_" . $entries[4];
                $found = 1;
            }
            last if $found;
        }
    } else {
        $k = $stnames{$entries[0]}{'loc'};
        $found = 1;
    } 

    if ( ! $found ) {
        warn "not found in weather_stations.desktop.in: $entries[0]\t$entries[5]\t$entries[3]\n";
        next ;
    }

    my $name = $entries[3] ;
    $name =~ s/\s+$//; # remove last space from the name
    $name =~ s/\s/\\\\\ /g; # replace space with \\space

    my ($v1,$v2) ;
    $v1 = $stnames{$entries[0]}{'v1'} if exists $stnames{$entries[0]}{'v1'};
    $v2 = $stnames{$entries[0]}{'v2'} if exists $stnames{$entries[0]}{'v2'};
    $v1 = "-------" if !$v1;
    $v2 = "---" if !$v2;

    $data{$k}{'loc'}[++$#{$data{$k}{'loc'}}] = $name ." ".$entries[0] ." $v1 $v2";
}
close(FDST);

#print Dumper \%data;

## write output to weather_stations.desktop

open(FDWSTOUT, ">", "weather_stations.desktop") || die "can not open file $!";

print FDWSTOUT "[Main]" . "\n";
print FDWSTOUT "regions=" . $data{'Main'}{'regions'} . "\n";
print FDWSTOUT "\n";

my @regions = split (/\s+/, $data{'Main'}{'regions'});

foreach my $r (@regions) {
	print FDWSTOUT "[$r]" . "\n";
	print FDWSTOUT "name=" . $data{$r}{'name'} . "\n";
	foreach my $f (keys %{$data{$r}}) {
		next if $f eq 'states';
		next if $f eq 'name';
		print FDWSTOUT $f . "=" . $data{$r}{$f} . "\n";
	}
	print FDWSTOUT "states=" . $data{$r}{'states'} . "\n";
	print FDWSTOUT "\n";

	my @states = split (/\s+/, $data{$r}{'states'});

	foreach my $s (@states) {
		my $k = "$r" . "_" . "$s";
        print FDWSTOUT "[" . $k . "]\n";
        print FDWSTOUT "name=" . $data{$k}{'name'} . "\n";

		for ( my $i=0; $i <= $#{$data{$k}{'loc'}}; $i++ ) {
			print FDWSTOUT "loc" . $i . "=" . $data{$k}{'loc'}[$i] . "\n";
		}
		print FDWSTOUT "\n";
	}
}
close(FDWSTOUT);