#!python3

"""
MIT License

Copyright (c) 2021 Baptiste Cecconi (Observatoire de Paris, PADC/MASER)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

__author__ = 'Baptiste Cecconi'
__copyright__ = 'Copyright 2021, Baptiste Cecconi, PADC/MASER'
__credits__ = ['Baptiste Cecconi']
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = 'Baptiste Cecconi'
__email__ = 'baptiste.cecconi@obspm.fr'
__status__ = "development"

from tfcat.feature import Feature, FeatureCollection, CRS
from tfcat.geometry import MultiPoint
from tfcat.codec import dump
from scipy.io import readsav
from pathlib import Path
from astropy.time import Time
from astropy.units import Unit as u
import sys
import shlex, subprocess


def exec_command(command_line, verbose=False):
    if verbose:
        print(f'Running: {command_line}\n')
    args = shlex.split(command_line)
    p = subprocess.run(args, capture_output=True)
    if verbose:
        print(p)


def converter(input_file, verbose=False):
    """
    Converts a .THP file into a TFCat JSON file

    :param input_file: Input file path
    :type input_file: str or Path
    """

    # Converting .thp file into intermediate .sav file.
    print('preparing data...')

    # This works in bash, with the IDL configured (modified next line if needed)
    IDL_BIN_DIR = "/Applications/harris/idl87/bin"

    tmp_file_sav = 'tmp_file.sav'

    command_line = f"""{IDL_BIN_DIR}/idl -e "thp_file_read, '{str(input_file)}', dat & save,file='{tmp_file_sav}', dat & exit" """

    if verbose:
        print(command_line)
    exec_command(command_line, verbose=verbose)

    # loading data from intermediate .sav file
    print('loading data...')

    raw_data = readsav(tmp_file_sav)

    # extracting data:
    tmin = Time(raw_data['dat']['TMIN'][0], format='unix')
    tmax = Time(raw_data['dat']['TMAX'][0], format='unix')
    fmin = raw_data['dat']['FMIN'][0] * u('Hz')
    fmax = raw_data['dat']['FMAX'][0] * u('Hz')
    nop = raw_data['dat']['NOP'][0]
    area = raw_data['dat']['AREA'][0]
    quality = raw_data['dat']['QUALITY'][0]

    id_border = raw_data['dat']['I01_BORDER'][0]
    tf_border = raw_data['dat']['TF_BORDER'][0]

    # setting up Feature list (of MultiPoint type items):
    print('building list of Features...')

    events = []
    for i in range(len(tmin)):
        events.append(Feature(
            id=i,
            geometry=MultiPoint(
                [(float(tt), float(ff)) for tt, ff in tf_border[id_border[i][0]:id_border[i][1]]]
            ),
            properties={
                'nop': int(nop[i]),
                'area': float(area[i]),
                'quality': int(quality[i])
            },
            bbox=[float(tmin[i].unix), float(fmin[i].value), float(tmax[i].unix), float(fmax[i].value)]
        ))

    properties = {
        "instrument_host_name": raw_data['dat']['PROBE'][0].decode('ascii'),
        "instrument_name": "RPWS",
        "receiver_name": "HFR",
        "title": "Catalogue of Faraday Rotation (FR) patches identified in Saturn Kilometric "
                 "Radiation (SKR) observations by Cassini/RPWS/HFR",
        "authors": [{
            "GivenName": "Ulrich",
            "FamilyName": "Taubenschuss",
            "ORCID": "https://orcid.org/0000-0003-4810-6958",
            "Affiliation": "https://ror.org/04vtzcr32"
        }, {
            "GivenName": "Baptiste",
            "FamilyName": "Cecconi",
            "ORCID": "https://orcid.org/0000-0001-7915-5571",
            "Affiliation": "https://ror.org/02eptjh02"
        }, {
            "GivenName": "Laurent",
            "FamilyName": "Lamy",
            "ORCID": "https://orcid.org/0000-0002-8428-1369",
            "Affiliation": "https://ror.org/02eptjh02"
        }],
        "bib_reference": "TBD",
        "doi": "10.25935/R11G-6J63",
        "publisher": "PADC",
        "version": "1.0"
    }

    fields = {
        "quality": {
            "info": "Quality parameter (this is biased strongly by my personal judgement, from visual inspection "
                    "of how clear the FR-fringes are visible in the Re{VuVw*} and Re{VvVw*}",
            "values": {
                "-1": "not set",
                "1": "good",
                "2": "medium",
                "3": "bad quality"
            },
            "datatype": "int",
            "ucd": "meta.code.flag"
        },
        "area": {
            "info": "Area in the time-spectral plane",
            "unit": "s.Hz",
            "datatype": "float",
            "ucd": "em.freq;em.radio"
        },
        "nop": {
            "info": "number of spectral points occupied by an FR-patch (i.e., not just from the borderline, but "
                    "all points surrounded by that line)",
            "datatype": "int",
            "ucd": "meta.number"
        },
    }

    crs = CRS({
        "name": "Time-Frequency",
        "properties": {
            "time_coords": {
                "id": "unix",
                "name": "Timestamp (Unix Time)",
                "unit": "s",
                "time_origin": "1970-01-01T00:00:00.000Z",
                "time_scale": "TT"
            },
            "spectral_coords": {
                "name": "Frequency",
                "unit": "Hz"
            },
            "ref_position": {
                "id": "Cassini"
            }
        }
    })

    # writing to file
    print('writing to files...')

    # Split into yearly catalogues:
    yearly_catalogues = dict([(str(year), []) for year in range(2006, 2018)])
    for feature in events:
        tmin_year = crs.time_converter(feature.tmin).isot[0:4]
        yearly_catalogues[tmin_year].append(feature)

    maser_doi = properties['doi'].lower()
    maser_content_url = f'https://maser.obspm.fr/doi/{maser_doi}/content/'

    print(f'|{{{{Year}}}}|{{{{# of Events}}}}|{{{{File}}}}|{{{{Start Time}}}}|{{{{End Time}}}}|')
    for year, year_catalogue in yearly_catalogues.items():
        if len(year_catalogue) != 0:
            year_collection = FeatureCollection(
                features=year_catalogue,
                properties=properties,
                fields=fields,
                crs=crs
            )
            year_collection.properties['time_min'] = crs.time_converter(year_catalogue[0].tmin).isot
            year_collection.properties['time_max'] = crs.time_converter(year_catalogue[-1].tmax).isot

            year_file = f'cassini_faraday_patches_{year}.json'
            with open(year_file, 'w') as f:
                dump(year_collection, f)
            print(f'|{year}|{len(year_catalogue)}|[{year_file}->{maser_content_url}{year_file}]|' +
                  f'{year_collection.properties["time_min"]}|{year_collection.properties["time_max"]}|')
        else:
            print(f'|{year}|{len(year_catalogue)}||||')

    # cleaning temporay files
    print('clean up...')

    Path(tmp_file_sav).unlink()

# Upload files:
# scp cassini_faraday_patches_20??.json vmmaser_rpws:/volumes/kronos/doi/10.25935/r11g-6j63/content/.


if __name__ == "__main__":

    args = sys.argv[1:]

    verbose = False
    if '-v' in args:
        verbose = True
        args.remove('-v')

    if len(args) == 0:
        raise IndexError('Missing arguments')

    input_file = Path(args[0])
    if not input_file.exists():
        raise FileNotFoundError(f"Input file doesn't exist: '{input_file}'")

    if len(args) > 1:
        raise IndexError('Too many arguments')

    if verbose:
        print(f'Input file: {input_file}')

    converter(input_file, verbose=verbose)
