/**
 * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of the Liferay Enterprise
 * Subscription License ("License"). You may not use this file except in
 * compliance with the License. You can obtain a copy of the License by
 * contacting Liferay, Inc. See the License for the specific language governing
 * permissions and limitations under the License, including but not limited to
 * distribution rights of the Software.
 *
 *
 *
 */

package com.liferay.portal.xuggler;

import com.liferay.petra.log4j.Log4JUtil;
import com.liferay.petra.string.StringBundler;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.xuggler.Xuggler;
import com.liferay.portal.kernel.xuggler.XugglerInstallException;
import com.liferay.portal.util.JarUtil;
import com.liferay.portal.util.PrefsPropsUtil;
import com.liferay.portal.util.PropsValues;

import com.xuggle.ferry.JNILibraryLoader;
import com.xuggle.xuggler.IContainer;

import java.net.URL;

import java.nio.file.Paths;

/**
 * @author Alexander Chow
 */
public class XugglerImpl implements Xuggler {

	@Override
	public void installNativeLibraries(String name, String sha1)
		throws Exception {

		try {
			if (Validator.isNotNull(sha1)) {
				JarUtil.downloadAndInstallJar(
					new URL(PropsValues.XUGGLER_JAR_URL + name),
					Paths.get(PropsValues.LIFERAY_LIB_PORTAL_DIR, name), sha1);
			}
			else {
				JarUtil.downloadAndInstallJar(
					new URL(PropsValues.XUGGLER_JAR_URL + name),
					Paths.get(PropsValues.LIFERAY_LIB_PORTAL_DIR, name));
			}

			_nativeLibraryCopied = true;
		}
		catch (Exception exception) {
			throw new XugglerInstallException.MustInstallJar(name, exception);
		}
	}

	@Override
	public boolean isEnabled() {
		return isEnabled(true);
	}

	@Override
	public boolean isEnabled(boolean checkNativeLibraries) {
		boolean enabled = false;

		try {
			enabled = PrefsPropsUtil.getBoolean(
				PropsKeys.XUGGLER_ENABLED, PropsValues.XUGGLER_ENABLED);
		}
		catch (Exception exception) {
			if (_log.isWarnEnabled()) {
				_log.warn(exception, exception);
			}
		}

		if (!checkNativeLibraries) {
			return enabled;
		}

		if (enabled) {
			return isNativeLibraryInstalled();
		}

		return false;
	}

	@Override
	public boolean isNativeLibraryCopied() {
		return _nativeLibraryCopied;
	}

	@Override
	public boolean isNativeLibraryInstalled() {
		if (_nativeLibraryInstalled) {
			return _nativeLibraryInstalled;
		}

		String originalLevel = Log4JUtil.getOriginalLevel(
			JNILibraryLoader.class.getName());

		try {
			Log4JUtil.setLevel(JNILibraryLoader.class.getName(), "OFF", false);

			IContainer.make();

			_nativeLibraryInstalled = true;
		}
		catch (NoClassDefFoundError ncdfe) {
			informAdministrator(ncdfe.getMessage());
		}
		catch (UnsatisfiedLinkError ule) {
			informAdministrator(ule.getMessage());
		}
		finally {
			Log4JUtil.setLevel(
				JNILibraryLoader.class.getName(), originalLevel, false);
		}

		return _nativeLibraryInstalled;
	}

	protected void informAdministrator(String errorMessage) {
		if (!_informAdministrator || !_log.isWarnEnabled()) {
			return;
		}

		_informAdministrator = false;

		StringBundler sb = new StringBundler(7);

		sb.append("Liferay does not have the Xuggler native libraries ");
		sb.append("installed. In order to generate video and audio previews, ");
		sb.append("please follow the instructions for Xuggler in the Server ");
		sb.append("Administration section of the Control Panel at: ");
		sb.append("http://<server>/group/control_panel/manage/-/server");
		sb.append("/external-services. Warning: ");
		sb.append(errorMessage);

		_log.warn(sb.toString());
	}

	private static final Log _log = LogFactoryUtil.getLog(XugglerImpl.class);

	private static boolean _informAdministrator = true;
	private static boolean _nativeLibraryCopied;
	private static boolean _nativeLibraryInstalled;

}