# AUTOGENERATED! DO NOT EDIT! File to edit: ../notebooks/07_diviner.ipynb.

# %% auto 0
__all__ = ['hostname', 'headerstring', 'DataManager', 'parse_header_line', 'L1AHeader', 'read_l1a_data', 'get_data_path']

# %% ../notebooks/07_diviner.ipynb 3
import socket
from pathlib import Path

import hvplot.xarray  # noqa
import pandas as pd
from .config import config
from .utils import url_retrieve
from yarl import URL

# %% ../notebooks/07_diviner.ipynb 4
hostname = socket.gethostname()
if hostname.startswith("luna") and hostname.endswith("diviner.ucla.edu"):
    storage_root = Path("/q/marks/feidata/DIV:opsL1A/data")
else:
    storage_root = config.storage_root / "missions/lro/diviner"

# %% ../notebooks/07_diviner.ipynb 5
class DataManager:
    def __init__(self, tstr):
        self.tstr = tstr

    @property
    def year(self):
        return self.tstr[:4]

    @property
    def yearmonth(self):
        return self.tstr[:6]

    @property
    def yearmonthday(self):
        return self.tstr[:8]

    @property
    def volume(self):
        if int(self.year) <= 2016:
            vol = 1
        else:
            vol = 2
        return vol

    @property
    def base_url(self):
        return URL(
            f"https://pds-geosciences.wustl.edu/lro/lro-l-dlre-2-edr-v1/lrodlr_{str(self.volume).zfill(4)}/data/"
        )

    @property
    def url(self):
        return self.base_url / str(
            Path(self.year, self.yearmonth, self.yearmonthday, f"{self.tstr}_edr.tab")
        )

    @property
    def local_path(self):
        end = self.url.parts[-4:]
        return storage_root / Path(*end)

    def download(self, overwrite=False):
        if self.local_path.exists() and not overwrite:
            print("File exists. Use `overwrite=True` to get a fresh copy.")
            return
        self.local_path.parent.mkdir(parents=True, exist_ok=True)
        url_retrieve(self.url, self.local_path)

# %% ../notebooks/07_diviner.ipynb 8
headerstring = (
    "Q, DATE, UTC, SCLK, SOUNDING, FROM_PKT, PKT_COUNT, SAFING, SAFED, FREEZING, FROZEN, ROLLING, DUMPING, MOVING, TEMP_FAULT,   SC_TIME_SECS,   SC_TIME_SUBS, TICKS_PKT_START, TICKS_AT_SC_TIME, OST_INDEX, EST_INDEX, SST_INDEX, LAST_AZ_CMD, LAST_EL_CMD, FPA_TEMP, FPB_TEMP, BAFFLE_A_TEMP, BAFFLE_B_TEMP, BB_1_TEMP, OBA_1_TEMP, ERROR_TIME, ERROR_ID,  ERROR_DETAIL , ERROR_COUNT, COMMANDS_RECEIVED, COMMANDS_EXECUTED, COMMANDS_REJECTED,    LAST_COMMAND_REC ,      CMD,  REQ_ID , LAST_TIME_COMMAND, LAST_EQX_PREDICTION, HYBRID_TEMP, FPA_TEMP_CYC, FPB_TEMP_CYC, BAFFLE_A_TEMP_CYC, BAFFLE_B_TEMP_CYC, OBA_1_TEMP_CYC, OBA_2_TEMP, BB_1_TEMP_CYC, BB_2_TEMP, SOLAR_TARGET_TEMP, YOKE_TEMP, EL_ACTUATOR_TEMP, AZ_ACTUATOR_TEMP,  MIN_15V, PLU_15V, SOLAR_BASE_TEMP, PLU_5V, "
    "A1_01, A1_02, A1_03, A1_04, A1_05, A1_06, A1_07, A1_08, A1_09, A1_10, A1_11, A1_12, A1_13, A1_14, A1_15, A1_16, A1_17, A1_18, A1_19, A1_20, A1_21, A2_01, A2_02, A2_03, A2_04, A2_05, A2_06, A2_07, A2_08, A2_09, A2_10, A2_11, A2_12, A2_13, A2_14, A2_15, A2_16, A2_17, A2_18, A2_19, A2_20, A2_21, A3_01, A3_02, A3_03, A3_04, A3_05, A3_06, A3_07, A3_08, A3_09, A3_10, A3_11, A3_12, A3_13, A3_14, A3_15, A3_16, A3_17, A3_18, A3_19, A3_20, A3_21, A4_01, A4_02, A4_03, A4_04, A4_05, A4_06, A4_07, A4_08, A4_09, A4_10, A4_11, A4_12, A4_13, A4_14, A4_15, A4_16, A4_17, A4_18, A4_19, A4_20, A4_21, A5_01, A5_02, A5_03, A5_04, A5_05, A5_06, A5_07, A5_08, A5_09, A5_10, A5_11, A5_12, A5_13, A5_14, A5_15, A5_16, A5_17, A5_18, A5_19, A5_20, A5_21, A6_01, A6_02, A6_03, A6_04, A6_05, A6_06, A6_07, A6_08, A6_09, A6_10, A6_11, A6_12, A6_13, A6_14, A6_15, A6_16, A6_17, A6_18, A6_19, A6_20, A6_21, B1_01, B1_02, B1_03, B1_04, B1_05, B1_06, B1_07, B1_08, B1_09, B1_10, B1_11, B1_12, B1_13, B1_14, B1_15, B1_16, B1_17, B1_18, B1_19, B1_20, B1_21, B2_01, B2_02, B2_03, B2_04, B2_05, B2_06, B2_07, B2_08, B2_09, B2_10, B2_11, B2_12, B2_13, B2_14, B2_15, B2_16, B2_17, B2_18, B2_19, B2_20, B2_21, B3_01, B3_02, B3_03, B3_04, B3_05, B3_06, B3_07, B3_08, B3_09, B3_10, B3_11, B3_12, B3_13, B3_14, B3_15, B3_16, B3_17, B3_18, B3_19, B3_20, B3_21"
)


def parse_header_line(line):
    """Parse header lines.

    >>> s = ' a   b  c    '
    >>> parse_header_line(s)
    ['a', 'b', 'c']
    >>> s = '  a, b  ,   c '
    >>> parse_header_line(s)
    ['a', 'b', 'c']
    """
    line = line.strip("#")
    if "," in line:
        newline = line.split(",")
    else:
        newline = line.split()
    return [i.strip().lower() for i in newline]


class L1AHeader:
    # beware: parse_header_line converts to lower case!
    columns = parse_header_line(headerstring)

    tel1cols = [
        "a{0}_{1}".format(i, str(j).zfill(2)) for i in range(1, 7) for j in range(1, 22)
    ]
    tel2cols = [
        "b{0}_{1}".format(i, str(j).zfill(2)) for i in range(1, 4) for j in range(1, 22)
    ]

    datacols = tel1cols + tel2cols

    metadatacols = list(set(columns) - set(datacols))
    metadatacols.sort()


def read_l1a_data(fname, nrows=None):
    df = pd.io.parsers.read_csv(
        fname,
        names=L1AHeader.columns,
        na_values="-9999",
        skiprows=8,
        skipinitialspace=True,
    )
    return df
    return parse_times(df)

# %% ../notebooks/07_diviner.ipynb 17
def get_data_path(tstr):
    dm = DataManager(tstr)
    if not dm.local_path.exists():
        dm.download()
    return dm.local_path
