package com.eactive.eai.rms.onl.loader.controller;

import java.nio.charset.StandardCharsets;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.onl.loader.service.DeployResourceDownloadServiceFactory;
import com.eactive.eai.rms.onl.loader.service.enm.ResourceType;
import com.eactive.eai.rms.onl.loader.vo.RuleFileResource;

@Controller
@RequestMapping({ "/deployresource" })
public class DeployResourceDownloadController extends BaseController implements InterceptorSkipController {

	@Autowired
	private DeployResourceDownloadServiceFactory serviceFactory;

	@RequestMapping({ "/{serviceType}/{resourceType}/{resourceName}/download.do" })
	public ResponseEntity<String> download(@PathVariable String serviceType, @PathVariable String resourceType,
			@PathVariable String resourceName) {

		/** Invalid serviceType Error **/
		if (!DataSourceTypeManager.getDataSourceTypeNames().contains(serviceType.toUpperCase()))
			return ResponseEntity.internalServerError()
					.contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
					.body("Invalid ServiceType:" + serviceType);

		try {

			RuleFileResource resource = serviceFactory.create(serviceType).getResource(serviceType,
					ResourceType.valueOf(resourceType.toUpperCase()), resourceName);

			return ResponseEntity.ok().header("Content-Disposition", "attachment; filename=" + resource.getFileName())
					.contentType(new MediaType("text", "plain", StandardCharsets.UTF_8))
					.body(resource.getFileContent());

		} catch (Exception e) {

			logger.error(e);
			return ResponseEntity.internalServerError()
					.contentType(new MediaType("text", "plain", StandardCharsets.UTF_8)).body(e.getMessage());
		}

	}

}