from pydarm.cmd._report import Report
import nds2 as nds

def m_trend_round(x, base=60):
    
    return int(base * round(float(x)/base))


def get_lock_state(report_ID):

    r = Report.find(report_ID)    # get report
    t = int(r.id_gpstime().gps()) # find GPS time when measurement was taken
    hours = 6                     # how far back in time do we want to look?

    print("Measurement {} was taken at GPS time = {:d} s.".format(report_ID, t))

    conn = nds.connection('h1nds1', 8088)
    conn.set_parameter('GAP_HANDLER', 'STATIC_HANDLER_ZERO')
    buff_lock = conn.fetch(m_trend_round(t-(3600*hours)), m_trend_round(t), ['H1:GRD-ISC_LOCK_STATE_N.mean,m-trend']) # read in lock state minute trend data

    lock_data = buff_lock[0].data
    rev_lock_data = lock_data[::-1]

    for i in range(len(lock_data)): # figure out when detector achieved lock relative to measurement

        if i == 0 and rev_lock_data[i] < 600:
            print("Detector was NOT locked during this measurement (state = {}).\n".format(lock_data[-1]))
            lock_state = "Not locked"
            time_locked = 0
            break
        elif rev_lock_data[i] >= 600:
            if i == len(lock_data)-1:
                print("Detector was locked at least {} hours before measurement.\n".format(hours))
                lock_state = "Locked"
                time_locked = str(hours) + "+"
                break
            else:
                continue
        elif rev_lock_data[i] < 600 and i+10 < len(lock_data) and rev_lock_data[i+10] >= 600:
            print("Detector only briefly lost lock (< 10 mins). Investigate?\n")
        else:
            print("Detector achieved lock {:.1f} hours before measurement.\n".format((i)/60))
            lock_state = "Locked"
            time_locked = round(i/60, 1)
            break

    return report_ID, str(t), lock_state, str(time_locked)


# run some examples
example_1 = get_lock_state("20230504T055052Z")
example_2 = get_lock_state("20230505T200419Z")
example_3 = get_lock_state("20230823T213958Z")
#report_IDs = ["20230504T055052Z", "20230505T012609Z", "20230505T174611Z", "20230505T200419Z", "20230506T182203Z", "20230508T180014Z", "20230509T070754Z", "20230510T062635Z", "20230517T163625Z", "20230616T161654Z",
#              "20230620T234012Z", "20230621T191615Z", "20230621T211522Z",  "20230628T015112Z", "20230716T034950Z", "20230727T162112Z", "20230802T000812Z", "20230817T214248Z", "20230823T213958Z", "20230830T213653Z",
#              "20230906T220850Z", "20230913T183650Z", "20230928T193609Z", "20231004T190945Z", "20231018T190729Z", "20231027T203619Z"]