package org.codiki.core.services;

import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

import org.apache.commons.lang.RandomStringUtils;
import org.codiki.core.constant.FileEnum;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileUploadService {
	/** Length of uploaded file names. */
	private static final int DESTINATION_IMAGE_NAME_LENGTH = 30;
	
	/**
	 * Builds the destination file name, which is a random string with 30 char
	 * length.
	 * 
	 * @return The file name.
	 */
	private String buildDestinationFileName() {
		return RandomStringUtils.randomAlphanumeric(DESTINATION_IMAGE_NAME_LENGTH);
	}
	
	public String uploadProfileImage(final MultipartFile pFile) {
		return uploadFile(pFile, FileEnum.FOLDER_PROFILE_IMAGES);
	}
	
	public String uploadImage(final MultipartFile pFile) {
		return uploadFile(pFile, FileEnum.FOLDER_IMAGE);
	}
	
	private String uploadFile(final MultipartFile pFile, final FileEnum pPath) {
		String result;
		try {
			result = buildDestinationFileName();
			Files.copy(pFile.getInputStream(), Paths.get(pPath.val()).resolve(result));
			return result;
		} catch (final Exception pEx) {
			// TODO : Refactor exception
			throw new RuntimeException();
		}
	}

	public Resource loadAvatar(final String pAvatarFileName) {
		return loadImage(pAvatarFileName, FileEnum.FOLDER_PROFILE_IMAGES);
	}
	
	public Resource loadImage(final String pImageLink) {
		return loadImage(pImageLink, FileEnum.FOLDER_IMAGE);
	}
	
	private Resource loadImage(final String pImageLink, final FileEnum pFilePath) {
		try {
			Path imageFile = Paths.get(pFilePath.val()).resolve(pImageLink);
			Resource imageResource = new UrlResource(imageFile.toUri());
			if(imageResource.exists() || imageResource.isReadable()) {
				return imageResource;
			} else {
				// TODO : Refactor exception
				throw new RuntimeException();
			}
		} catch(final MalformedURLException pEx) {
			// TODO : Refactor exception
			throw new RuntimeException();
		}
	}
}
