package com.adobe.primetime.reference.utils;

import java.net.MalformedURLException;
import java.net.URL;

public final class StringUtils {

    /**
     * Checks if the string is null or contains only spaces.
     * @param value the value to be checked
     * @return true if the string is really "empty" and false otherwise.
     */
    public static boolean isEmpty(String value) {
        return value == null || value.trim().isEmpty();
    }

    /**
     * Retrieves file extension for the provided url. This is needed for
     * automatically detecting the type of the media being provided.
     * @param url the url to be scanned for a file extension
     * @return the file extension of the stream or null if no extension was found.
     */
    public static String getFileExtension(String url) {
        String extension = null;

        try {
            URL actualUrl = new URL(url);
            String fileName = actualUrl.getFile();
            int lastPeriodIndex = fileName.lastIndexOf(".");
            if (lastPeriodIndex != -1) {
                // Extract extension from www.domain.com/test.m3u8 to m3u8
                extension = fileName.substring(lastPeriodIndex + 1).trim();
            }
            if (extension != null && extension.contains("?")) {
                // Extract extension from m3u8?key=value to m3u8
                lastPeriodIndex = extension.lastIndexOf("?");
                extension = extension.substring(0, lastPeriodIndex).trim();
            }
        } catch (MalformedURLException exception) {
            extension = null;
        }

        return extension;
    }

    private StringUtils() {}
}