#!/usr/bin/python3.6 -s

# Copyright (c) 2020 Paolo Patruno <p.patruno@iperbole.bologna.it>
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 
# 1. Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# 3. Neither the name of mosquitto nor the names of its
#   contributors may be used to endorse or promote products derived from
#   this software without specific prior written permission.
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

ARKIMETBASEPATH="/rmap/arkimet/"

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'rmap.settings'
from django.conf import settings

#disable unwanted initialization and error management of kivy
os.environ['KIVY_DOC_INCLUDE'] = "1"

from rmap import __version__
import rmap.settings
import argparse
import django
import dballe
#mport logging
from pathlib import Path

# go to share dir for virtualenv
ve=os.getenv("VIRTUAL_ENV")
if ve is not None:
    os.chdir(ve+"/share/rmap")
    
django.setup()

#types=["report_fixed","report_mobile","sample_fixed","sample_mobile"]
types=rmap.settings.BORINUD.keys()

parser = argparse.ArgumentParser(description='Create explorer fron dballe DSN (default) or arkimet; explorer are used by BORINUD to cache summaries. Call this periodically from crontab or whe DB is updated')
parser.add_argument('--version', action='version', version="%(prog)s "+__version__)
parser.add_argument('--writeexplorer',action="store_true", help="write explorer on permanent store")
parser.add_argument('--alltype',action="store_true", help="select ALL data level and type of data to elaborate")
parser.add_argument('--nodballe',action="store_true", help="disable build explorer for DBall.e")
parser.add_argument('--arkimet',action="store_true", help="build explorer for arkimet")
parser.add_argument('--type',  default=None, choices=types,help="select data level and type of data to elaborate")

args = parser.parse_args()


if (args.type is None and args.alltype == False):
    print ("select --type or --alltype")
    raise SystemExit(1)

if (args.type is not None):
    types=[args.type,]

print(" selected types: ", types)



for type in types:
    for source in rmap.settings.BORINUD[type]["SOURCES"]:
        if not args.nodballe:
            if (source["class"] == "borinud.utils.source.DballeDB"):
                indsn=source["url"]
                outexplorer=source["explorer"]
                print(indsn,outexplorer)
            
                # Create from database
                db = dballe.DB.connect(indsn)

                if args.writeexplorer:
                    with dballe.Explorer(outexplorer) as explorer:
                        with explorer.rebuild() as updater:
                            with db.transaction() as tr:
                                updater.add_db(tr)
                        print ("explorer created and written: ")
                        print (explorer.stats)

                else:
                    with dballe.Explorer() as explorer:
                        with explorer.rebuild() as updater:
                            with db.transaction() as tr:
                                updater.add_db(tr)
                        #updater.set_filter({"ident":"agrmet"})
                        print ("explorer created and NOT written: ")
                        print (explorer.all_reports)
                        print (explorer.all_levels)
                        print (explorer.all_tranges)
                        print (explorer.all_varcodes)
                        print (explorer.stats)

            else:
                print("Skip DBALLE source without defined explorer: ", indsn)


        if args.arkimet:

            if (source["class"] == "borinud.utils.source.ArkimetBufrDB"):
                outexplorer=source["explorer"]

                for path in Path(ARKIMETBASEPATH+type).rglob('*.bufr'):
                    file=path.as_posix()
                    print("elaborate: ",file)

                    # update from file
                    if (args.writeexplorer):
                        with dballe.Explorer(outexplorer) as explorer:
                            with explorer.update() as updater:
                                importer = dballe.Importer("BUFR")
                                with importer.from_file(file) as message:
                                    try:
                                        updater.add_messages(message)
                                    except Exception as e:
                                        print (e)
                            print ("updated from file")
                            print (explorer.stats)
                    else:
                        with dballe.Explorer() as explorer:
                            with explorer.update() as updater:
                                importer = dballe.Importer("BUFR")
                                with importer.from_file(file) as message:
                                    try:
                                        updater.add_messages(message)
                                    except Exception as e:
                                        print (e)
                            print ("updated from file")
                            print (explorer.all_reports)
                            print (explorer.all_levels)
                            print (explorer.all_tranges)
                            print (explorer.all_varcodes)
                            print (explorer.stats)
