"""
Advanced usage of sea data
==========================

"""
import km3compass as kc
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

#####################################################
# Initialising a readerOnline
# -------------------------
# Downloading run 9000 from ORCA6. This run is 10 minutes long,
# perfect for an example !

reader = kc.readerOnline("D_ORCA006", minrun=9000, maxrun=9000)

#####################################################
# Calibrate data
# -------------------------
#
# The calibration module is made to calibrate only one DOM. Therefore,
# we need to loop over the available module and calibrate them
# independantly. To limit the number of DB request, a db_agent is
# created beforehand. It will copy locally the tables needed from the
# DB, removing the need to contact the DB later.

df_calib = None
df_ahrscalibtable = None

db_agent = kc.calibration_DB_agent()

for modID in reader.module_IDs:
    try:
        calib = kc.calib_DB(reader, modID, db_agent=db_agent, verbosity=False)
        df_calib = pd.concat((df_calib, calib.df))
    except:
        print("failed for : {}".format(modID))

#####################################################
# Plot before and after per DU
# ----------------------------
#
# Now we can do a quick before/after calibration plot, DU per DU. In this
# example, the break limit the display to the first line, already
# enough for the example.

for duid in np.unique(reader.df.DUID):

    before_calib = reader.df[reader.df["DUID"] == duid]
    after_calib = df_calib[df_calib["DUID"] == duid]

    print("DU {}".format(duid))
    print(
        "\tDOMs before calibration : {}".format(len(np.unique(before_calib["DOMID"])))
    )
    print("\tDOMs after calibration : {}".format(len(np.unique(after_calib["DOMID"]))))

    # In order to display the 0, cheating a bit and adding a measurement in (0,0,0)

    zero = pd.DataFrame({"AHRS_H0": [0], "AHRS_H1": [0], "AHRS_H2": [0], "DOMID": [0]})
    after_calib = pd.concat((after_calib, zero))
    kc.plot_raw_results(before_calib, title="DU {}, Before calibration".format(duid))

    kc.plot_raw_results(after_calib, title="DU {}, After calibration".format(duid))
    break

plt.show()
