# -*- coding: utf-8 -*-

# PyNX - Python tools for Nano-structures Crystallography
#   (c) 2021-present : ESRF-European Synchrotron Radiation Facility
#       authors:
#         Vincent Favre-Nicolin, favre@esrf.fr

from os.path import realpath


def longest_common_prefix(string_list):
    """
    Find a common prefix between a list of strings (e.g. filenames)
    :param string_list: a list of strings for which we will search the common prefix,
        i.e. the longest first characters which belong to all strings
    :return: the string with the common prefix
    """
    c = ""
    break_ = False
    for i in range(1, len(string_list[0]) + 1):
        c = string_list[0][:i]
        for s in string_list[1:]:
            if len(s) < i + 1:
                break_ = True
                break
            if s[:i] != c:
                break_ = True
                break
        if break_:
            break
    return c


def replace_dir(path, old='RAW_DATA',
                new='PROCESSED_DATA'):
    """Convert e.g. 'some/path/RAW_DATA/other/path' to
    'some/path/PROCESSED_DATA/other/path'. This will
    first resolve the real path (removing any symbolic
    link in the path) before searching for RAW_DATA in the
    path string.

    :param path: the path to convert - may be absolute or
       relative, and may include symbolic links initially
       hiding the RAW_DATA path
    :param old: the old string to be replaced in the real path
    :param new: the new string to replace
    :return: the new path with the 'new' string replacing the 'old'
        one in the resolved path, or the original real path if 'old'
        was not found. Note that the new path needs to be created
        separately.
    """
    path0 = realpath(path)
    if len(old) < 3:
        raise RuntimeError(f"replace_dir(): old string (f{old}) is too short")
    if len(new) == 0:
        raise RuntimeError(f"replace_dir(): new string is empty !")
    if old not in path0:
        return path0
    return path0.replace('RAW_DATA', 'PROCESSED_DATA')
