import os

from . import core, global_actions, groups, utils


@core.cl_context.entry_point
def cl_import_m3u(group: groups.Group, d):
    d = d.replace("\r", "").split("\n")

    info = None

    for i in d:
        if i.strip().startswith("#EXTINF:"):
            info = i.strip().split(",")[-1]

        if i.strip() and not i.strip().startswith("#"):
            i = os.path.expanduser(i)
            try:
                if os.path.exists(i.strip()):
                    utils.new_cue_from_sound(group, i.strip())
                else:
                    # Try to find it wherever it may be.
                    # This is a fuzzy match that could in theory make mistakes.
                    i2 = core.resolve_sound_fuzzy(i)
                    if os.path.exists(i2):
                        utils.new_cue_from_sound(group, i2, name=info)
                    else:
                        global_actions.cl_event(
                            "board.error", "Error locating " + str(i)
                        )
            except Exception:
                global_actions.cl_event(
                    "board.error", "Error locating " + str(i)
                )

            info = None


def get_m3u(group: groups.Group, rel=None):
    "Convert the sounds mentioned in cues to m3u files."
    o = "#EXTM3U\r\n\r\n"

    for i in group.cues_ordered:
        if i.sound:
            try:
                c = group.resolve_media(i.sound, i)

                d = core.get_audio_duration(c)

                # If name not autogenerated, add it to playlist file
                n = "," + i.name
                if i.named_for_sound:
                    n = ""

                if d:
                    o += "#EXTINF:" + str(d) + n + "\r\n"
                else:
                    if (not i.rel_length) and i.length:
                        o += "#EXTINF:" + str(i.length) + n + "\r\n"

                h = os.path.expanduser("~")

                if c.startswith(h):
                    c = "~" + c[len(h) :]

                o += c + "\r\n"

            except Exception:
                pass

    return o
