#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------------------
# Script to produce MSLP Ground Pressure Overlays from EUMETCast channel E1B-DWDSAT
#
# Unfortunately E1B-DWDSAT has no colored DWD MSLP-charts as found on DWD OpenData:
# They disseminate dwda, dwdn 6 hourly, dwdc, dwdi 12 hourly, all black&white only!
# But they have an UKMO (XXL) 1728 x 2351 pixel MSLP analysis chart under the name:
# Z__C_EDZW_20220708193608_fax01,egrr_bwk_nt_p_000000_000000_202207081800_EGRR.tiff
# Users who want dwda 3 hourly and colored weather fronts must access DWD OpenData.
#
# This script should run in PyTROLL (base) environment under Windows and GNU/Linux.
# It expects a version of ImageMagick convert(.exe) to be installed on your system.
#
# CH-3123 Belp, 2022/12/10              License GPL3             (c) Ernst Lobsiger
# ---------------------------------------------------------------------------------

import os, sys, platform
from glob import glob
from datetime import datetime

OS = platform.system()

if OS == 'Linux':
    segdir = '/srv/E1B-DWDSAT'
    isbulk = False
    toodir = '/home/eumetcast/SPStools'
    datdir = '/home/eumetcast/SPSdata'
    # Do not touch the GNU/Linux stuff below this line
    convert='convert'
    ob = ' \( '
    cbc = ' \) -composite'
elif OS == 'Windows':
    segdir = 'Z:/E1B-DWDSAT'
    isbulk = False
    toodir = 'C:/SPStools'
    datdir = 'D:/SPSdata'
    # Do not touch the Windows stuff below this line
    convert = toodir + '/exefiles/convert.exe'
    ob = ' ^( '
    cbc = ' ^) -composite'
else:
    sys.exit('Sorry, OS ' + OS + ' seems unsupported yet ...')

# Make dwda, dwdn, dwdc, and dwdi charts
do_dwdx = False
# Make the eXtra large "Bracknell" chart
do_ukmox = True

# ****************************************************
# Touch this stuff below only if you know what you do!
# ****************************************************

# Processed MSLP overlays go into this directory (must exist)
# Sub directories dwda, dwdc, dwdn, dwdi, ukmox (must exist)
mslpdir = datdir + '/overlays'
# Threshold for B&W processing
threshold = ' -threshold 80%'


# Get useful info back from UNIX time now
if not isbulk:
    dt = datetime.now()
    Yea = dt.strftime('%Y')
    Mon = dt.strftime('%m')
    Day = dt.strftime('%d')
    segdir = segdir + '/' + Yea + '/' + Mon +'/' + Day

# Directory must exist
try:
   os.chdir(segdir)
except:
   sys.exit('Cannot change to segdir directory ' + segdir + ' ...')

# Used DWD colors ("" for GNU/Linux only?)
black='"#000000"'
white='"#ffffff"'
# Added for dwdi
gray20='"#333333"'
# Threshold for B&W charts
threshold = ' -threshold 80%'
areaX = 'ukmox'

if do_dwdx:
    # Process all DWD monochrome overlays (does not work under Windows this way)
    for f in glob('Z__C_EDZW*dwd*WV12SW.png'):
       area=f[42:46]
       if area == 'dwda':
          print('Processing Western Europe monochrome')
          Dat=f[63:75]
       elif area == 'dwdn':
          print('Processing North Atlantic monochrome')
          Dat=f[64:76]
       elif area == 'dwdc':
          print('Processing Stereographic  monochrome')
          Dat=f[63:75]
       else:
          continue
       # Windows cannot handle ',' in file names
       f = '"'+f+'"'
       chart = mslpdir+'/'+areaX+'/'+area+'-bb-'+Dat+'.png'
       if not os.path.exists(chart):
           # DOESN'T WORK UNDER WINDOWS: cmdstr = convert+' '+f+threshold+' -transparent '+white+' PNG32:'+chart
           cmdstr = convert+' '+f+threshold+' -negate -transparent black -fill black -opaque white PNG32:'+chart
           os.system(cmdstr)
       chart = mslpdir+'/'+areaX+'/'+area+'-ww-'+Dat+'.png'
       if not os.path.exists(chart):
           cmdstr = convert+' '+f+threshold+' -negate -transparent '+black+' PNG32:'+chart
           os.system(cmdstr)
    # Process DWD ICON13 MSLP overlays. These files have different colors from text antialiasing. Pressure lines are gray20.
    for f in glob('Z__C_EDZW*p00_na*WV11.png'):
       area='dwdi'
       Dat=f[58:70]
       # Windows cannot handle ',' in file names
       f = '"'+f+'"'
       print('Processing Central Europe monochrome')
       chart = mslpdir+'/'+areaX+'/'+area+'-bb-'+Dat+'.png'
       if not os.path.exists(chart):
           cmdstr = convert+' '+f+threshold+ob+f+' -fill '+black+' -opaque '+gray20+' +transparent '+black+cbc+' -transparent '+white+' PNG32:'+chart
           os.system(cmdstr)
       chart = mslpdir+'/'+areaX+'/'+area+'-ww-'+Dat+'.png'
       if not os.path.exists(chart):
           cmdstr = convert+' '+f+threshold+ob+f+' -fill '+black+' -opaque '+gray20+' +transparent '+black+cbc+' -negate -transparent '+black+' PNG32:'+chart
           os.system(cmdstr)


if do_ukmox:
    # Process UKMO (XXL = 2351 x 1589) MSLP analysis charts
    for f in glob('Z__C_EDZW*bwk_nt_p_000000*.tiff'):
       area='ukmox'
       Dat=f[59:71]
       # Windows cannot handle ',' in file names
       f = '"'+f+'"'
       print('Processing DWD (XXL) Bracknell chart')
       chart = mslpdir+'/'+areaX+'/'+area+'-bb-'+Dat+'.png'
       if not os.path.exists(chart):
           cmdstr = convert+' '+f+' -rotate -90 -crop 2345x1583+3+72 -bordercolor '+black+' -border 3x3'+threshold+' -transparent '+white+' PNG32:'+chart
           os.system(cmdstr)
       chart = mslpdir+'/'+areaX+'/'+area+'-ww-'+Dat+'.png'
       if not os.path.exists(chart):
           cmdstr = convert+' '+f+' -rotate -90 -crop 2345x1583+3+72 -bordercolor '+black+' -border 3x3'+threshold+' -negate -transparent '+black+' PNG32:'+chart
           os.system(cmdstr)

