# -*- coding: utf-8 -*-
"""
Created on Wed Dec 25 09:17:32 2024

@author: ym
"""
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime

sys.path.append(r"D:\DetectTracking")

from contrast.utils.event import ShoppingEvent
from tracking.utils.read_data import read_weight_sensor, extract_data_realtime, read_tracking_output_realtime
from tracking.utils.read_data import read_process

def time_std2stamp(custom_time):
    date_part = custom_time.split('-')[0]
    time_part = custom_time.split('-')[1]
    ms_part = int(custom_time.split('-')[2])
    standard_time = f"{date_part} {time_part[:2]}:{time_part[2:4]}:{time_part[4:]}"
    dt = datetime.strptime(standard_time, "%Y%m%d %H:%M:%S")
    timestamp = int(dt.timestamp() * 1000) + ms_part
    return timestamp

def time_stamp2std(timestamp):
    if isinstance(timestamp, float) or isinstance(timestamp, str):
        timestamp = int(timestamp)
    ms = timestamp%1000
    times = timestamp//1000
    std_time = datetime.fromtimestamp(times)
    stdtime = std_time.strftime("%Y%m%d-%H%M%S") + '-' +str(ms)
    return stdtime

def get_timeduring_weight(procpath):
    eventStart, eventEnd, weightValue = None, None, None
    if os.path.isfile(procpath):
        timeDict = read_process(procpath)
        if "eventStart" in timeDict.keys():
            eventStart = timeDict["eventStart"]
        if "eventEnd" in timeDict.keys():
            eventEnd = timeDict["eventEnd"]
        if "weightValue" in timeDict.keys():
            weightValue = timeDict["weightValue"]
    return eventStart, eventEnd, weightValue

def event_devide(wpath):
    '''
    基于重力时序数据 _weight.data 进行事件切分
    '''
    # wpath = r'D:\全实时\source_data\2024122416\20241224-162658370_weight.data'
    
    tpath, _ = os.path.split(wpath)

    wsdata = read_weight_sensor(wpath)
    times, weights = wsdata[:, 0], wsdata[:, 1]
    Start, End = times[0], times[-1]
    
    evtpaths, evtTimeWeight = [], []
    for filename in os.listdir(tpath):
        filelist = filename.split('_')
        custom_time = filelist[0]
        evtpath = os.path.join(tpath, filename)
        if os.path.isdir(evtpath):
            stamp = time_std2stamp(custom_time)
            if stamp >= Start and stamp <= End:
                evtpaths.append(evtpath)
             
    for evtpath in evtpaths:
        evtname =  os.path.basename(evtpath)
        event = ShoppingEvent(evtpath, stype = "realtime")
        # try:
        #     event = ShoppingEvent(evtpath, stype = "realtime")
        # except Exception as e:
        #     print(f"Error is: {e}", evtname)
        
        '''读取事件的起止时间、重力变化值'''
        propath = os.path.join(evtpath, "process.data")
        evtStart, evtEnd, wgtValue = get_timeduring_weight(propath)
        evtTimeWeight.append((evtStart, evtEnd, wgtValue))


    '''重力变化曲线、事件起止区间'''
    fig, ax1 = plt.subplots(figsize=(16, 9), dpi=100)    
    ax1.plot(times-Start, weights, 'bo-', linewidth=1, markersize=3)
    ax1.set_title('Weight (gram)')
    for t0, t1, w in evtTimeWeight:
        min_diff = float('inf')
        index = None
        for i, t in enumerate(times):
            diff = abs(t0 - t)
            if diff < min_diff:
                min_diff = diff
                index = i
        w0 = weights[index]
        w1 = w0 + w
        ax1.plot((t0, t0) - Start, (w0, w1), 'r*-', linewidth=1, markersize=6)
        ax1.plot((t1, t1) - Start, (w0, w1), 'r*-', linewidth=1, markersize=6)
        ax1.plot((t0, t1) - Start, (w1, w1), 'r*-', linewidth=1, markersize=6)
    ax1.grid(True)
    plt.show()
    
    return plt
    
    
    




def main():
    tpath = r"D:\全实时\source_data\2024122416"
    rltpath = r"D:\全实时\result"
    for filename in os.listdir(tpath):
        bname = filename.split("_")[0]
        if filename.find("_weight.data") <= 0:
            continue
        wpath = os.path.join(tpath, filename)
        
        plt = event_devide(wpath)
        
        plt.savefig(os.path.join(rltpath, f'{bname}.png' ))  # svg, png, pdf

        print(filename)
        
    
    
    
    
    
    
    print("Done!")
          

if __name__ == "__main__":
    main()