## PARSE_SPREADSHEET
#
# Log:
# 11.05.2021 - Created function [1]
#
# Authors:
# [1] Alexander Smolka (alexander.smolka@tum.de)

"""
    parse_preadsheet(raw::CDataRaw)
    parse_spreadsheet(path::String)

**Comments**
- Exported spreadsheet data from COMSOL will write the field names as `<name> (<unit>)`.
  Since this format is assumed to determine the unit of the respective field,
  the respective file has to be in that format for this function to work.

!!! note "COMSOL Version"
    5.3.0.223

!!! note "Julia Version"
    1.6.0
"""
function parse_spreadsheet(raw::CDataRaw)
    # iniate n, u, & v
    n = String[]
    u = String[]
    v = Dict{String, Any}()

    # get keys (names of old dictionary)
    old_keys = collect(keys(raw.v))

    # update value dictionary with new names
    for i in 1:length(raw.field)
        # create new key (name) and unit of field by splotting the field string
        new_key, unit = _separatenameunit(old_keys[i])

        # add name and unit to respective vector
        push!(n, new_key)
        push!(u, unit)

        # add values from old dictionary to new dictionary
        v[new_key] = raw.v[old_keys[i]]
    end

    #
    return CDataParsedSpreadsheet(raw.path, raw.meta, n, u, v)
end
parse_spreadsheet(path::String) = parse_spreadsheet(read_spreadsheet(path))

## INTERNAL FUNCTIONS ======================================================= ##
function _separatenameunit(s::String)
    for i in length(s):-1:1
        if s[i] == '('
            return s[1:i-2], s[i+1:end-1]
        end
    end
end
