import struct, io, os
import pandas as pd
from datetime import datetime,timedelta

def readString(bytesStream):
    strLen = bytesStream.read(1)[0]
    
    if strLen < 255:
        string = bytesStream.read(strLen).decode()  
    else:
        strLen = struct.unpack("H", bytesStream.read(2))[0]  
        if strLen < 0xfffe:
            string = bytesStream.read(strLen).decode() 
        else:
            strLen = struct.unpack("I", bytesStream.read(4))[0] 
            string = bytesStream.read(strLen).decode() 
            
    return string

class RphData:
    def __init__(self):
        self._fileName = str()
        self._fileType = 'rph'
        self.properties = None

def readStringPython(bytesStream):
    length = int.from_bytes(bytesStream.read(2), "little", signed = False)
    # return bytesStream.unpack(str(length) + 's', length)
    return bytesStream.read(length).decode() 

def rphToDf(path):
    """
    Unpacks rph file into a dataframe
    
    Parameters
    ----------
    path : str
        Complete file path
        
    Returns
    -------
    RphData
        Structure containing most useful data

    """
    
    file = open(path, "rb")
    bytesArray = file.read()
    bytesStream = io.BytesIO(bytesArray)
    
    trends_names = []
    values = []
    timestamps = []
    properties = dict()
    
    properties['MagicNumber'] = int.from_bytes(bytesStream.read(4), "little", signed = False)
    properties['ArchiveType'] = int.from_bytes(bytesStream.read(4), "little", signed = False)
    properties['StartTotalSeconds'] = int.from_bytes(bytesStream.read(4), "little", signed = False)
    properties['EndTotalSeconds'] = int.from_bytes(bytesStream.read(4), "little", signed = False)
    properties['TimeScan'] = int.from_bytes(bytesStream.read(4), "little", signed = False)

## custom read

    properties['Source'] = readString(bytesStream) ### Different reading

    number_of_trends = int.from_bytes(bytesStream.read(2), "little", signed = False)
    
    for trend in range(number_of_trends):
        trends_names.append(readString(bytesStream))

    number_of_samples = int.from_bytes(bytesStream.read(4), "little", signed = False)
    
    for sample in range(number_of_samples):
        num = struct.unpack("H", bytesStream.read(2))[0] #trends
        
        row = []

        for element in range(num):
            row.append(struct.unpack("f", bytesStream.read(4))[0])
            
        values.append(row)
        
    time_stamp_count = int.from_bytes(bytesStream.read(2), "little", signed = False)
    
    for timestamp in range(time_stamp_count):
        total_seconds = bytesStream.read(4) #time_t.TotalSeconds
        total_seconds = int.from_bytes(total_seconds, "little", signed = False)
        dt = datetime.fromtimestamp(total_seconds)
        
        # milliseconds = struct.unpack("H", bytesStream.read(2))[0]   #dt.Millisecond
        milliseconds = int.from_bytes(bytesStream.read(2), "little", signed = False)
        dt += timedelta(milliseconds=milliseconds)
        
        # TimeZone.CurrentTimeZone.GetUtcOffset(dt).TotalMinutes
        timezone = int.from_bytes(bytesStream.read(2), "little", signed = True)
        dt += timedelta(minutes=timezone)
        # dt.IsDaylightSavingTime() ? (short)1 : (short)0
        daylight = bytesStream.read(2)
        # 0 ???
        bytesStream.read(2)
        
        timestamps.append(dt)
            
    totals = int.from_bytes(bytesStream.read(4), "little", signed = True)
    
    dFrame = pd.DataFrame(values, columns=trends_names)
    dFrame.insert(0,"Timestamp", timestamps)
    
    data = RphData()
    data._fileName = os.path.basename(path)
    data.dataFrame = dFrame
    data.properties = properties
    return data

# data = rphToDf(r'C:\Users\LCastro\Ami\Eric Garza Sanchez - ElectrodeBreak\new\Event Logs Gerdau Jackson and Gerdau FortSmith #3\HeatLogs_20200323_20200923.rph')
# data = rphToDf(path = r"C:\Users\LCastro\Ami\Eric Garza Sanchez - ElectrodeBreak\Gerdau Jackson Quebraduras Oct-Nov\20201109-CIN-PH2-M1-08.10MWH-First Brake\Electrode Breakage Phase B Heat #63203561_firstbrake.rph")
# data = rphToDf(path = r"C:\Users\LCastro\Ami\Eric Garza Sanchez - ElectrodeBreak\new\Event Logs Gerdau Jackson and Gerdau FortSmith #3\Gerdau FortSmith #3 Electrode Breakage A Phase on Heat #73118533\EventLog_Preemptive CaveIn_20200819T070634Z.rph")
carblogs = rphToDf(r'C:\Users\LCastro\Downloads\SULB_RPH_files (1)\CarbLogs_2107200000.rph')
carblogsanalysis = rphToDf(r'C:\Users\LCastro\Downloads\SULB_RPH_files (1)\reporter-carblogsanalysis-20210714.rpd')
dailyreport = rphToDf(r'C:\Users\LCastro\Downloads\SULB_RPH_files (1)\reporter-dailyreport-20210720.rpd')
sulbanalysis = rphToDf(r'C:\Users\LCastro\Downloads\SULB_RPH_files (1)\reporter-sulbanalysus1-20210719.rpd')
SULB = rphToDf(r'C:\Users\LCastro\Downloads\SULB_RPH_files (1)\SULB_4892.rph')
sulb2 = rphToDf(r'C:\Users\LCastro\Downloads\SULB_RPH_files (1)\reporter-sulbanalysus1-20210619.rpd')