package com.github.aureliano.achmed.resources;

import org.apache.log4j.Logger;

import com.github.aureliano.achmed.AppConfiguration;
import com.github.aureliano.achmed.helper.StringHelper;
import com.github.aureliano.achmed.os.fs.IFileProvider;
import com.github.aureliano.achmed.resources.properties.FileProperties;
import com.github.aureliano.achmed.resources.properties.IResourceProperties;
import com.github.aureliano.achmed.types.EnsureFileStatus;

public class FileResource implements IResource {
	
	private static final Logger logger = Logger.getLogger(FileResource.class);
	
	private FileProperties properties;
	
	public FileResource() {
		this.properties = new FileProperties();
	}

	public FileResource(FileProperties properties) {
		this.properties = properties;
	}
	
	public void apply() {
		logger.info(" >>> Apply file resource to " + this.properties.getPath());
		
		this.properties.configureAttributes();
		IFileProvider provider = AppConfiguration.instance().getOperatingSystem().getDefaultFileProvider();
		provider.setFileProperties(this.properties);
		
		this.applyFilePermissions(provider);
		this.ensure(provider);
	}

	public void setProperties(IResourceProperties properties) {
		this.properties = (FileProperties) properties;
	}
	
	public IResourceProperties getProperties() {
		return this.properties;
	}

	public ResourceType type() {
		return ResourceType.FILE;
	}
	
	private void applyFilePermissions(IFileProvider provider) {
		if (!StringHelper.isEmpty(this.properties.getMode())) {
			logger.info("Setting file mode " + this.properties.getMode() + " to " + this.properties.getPath());
			provider.setFileMode();
		}
		
		if (!((StringHelper.isEmpty(this.properties.getGroup())) && (StringHelper.isEmpty(this.properties.getOwner())))) {
			provider.setFileOwner();
		}
	}
	
	private void ensure(IFileProvider provider) {
		if (EnsureFileStatus.ABSENT.equals(this.properties.getEnsure())) {
			logger.info("Apply file absence to " + this.properties.getPath());
			provider.ensureFileAbsence();
		} else {
			logger.info("Apply file presence to " + this.properties.getPath());
			provider.ensureFilePresence();
		}
	}
}
@@ -127,16 +127,70 @@
 ration;%0A
+import com.github.aureliano.achmed.helper.FileHelper;%0A
 import c
@@ -229,32 +229,32 @@
 r.StringHelper;%0A
-
 import com.githu
@@ -969,16 +969,40 @@
 utes();%0A
+%09%09this.amendPaths();%0A%09%09%0A
 %09%09IFileP
@@ -1430,24 +1430,24 @@
 pe type() %7B%0A
-
 %09%09return Res
@@ -1463,24 +1463,306 @@
 .FILE;%0A%09%7D%0A%09%0A
+%09private void amendPaths() %7B%0A%09%09this.properties.setPath(FileHelper.amendFilePath(this.properties.getPath()));%0A%09%09this.properties.setSource(FileHelper.amendFilePath(this.properties.getSource()));%0A%09%09this.properties.setTarget(FileHelper.amendFilePath(this.properties.getTarget()));%0A%09%7D%0A%09%0A
 %09private voi

Replace environment variables from path attributes.