package com.inkasso.factoring.code.service.impl;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.inkasso.factoring.code.config.GoldConstant;
import com.inkasso.factoring.code.model.CodeDTO;
import com.inkasso.factoring.code.service.CodeGeneratorService;
import com.inkasso.factoring.code.util.CompressUtil;
import com.inkasso.factoring.code.util.FreemarkerUtils;
import net.lingala.zip4j.exception.ZipException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CodeGeneratorServiceImpl implements CodeGeneratorService {

	@Autowired
	private GoldConstant goldConstant;

	@Override
	public String createFile(CodeDTO codeDTO) {
		String [][] flts = {{"entity","mapper","service","serviceImpl","dto","addRequest","queryRequest","editRequest","controller"},
				{"EntityDO.java","EntityDAO.java","EntityService.java","EntityServiceImpl.java","EntityDTO.java","AddEntityRequest.java","QueryEntityRequest.java","EditEntityRequest.java","EntityController.java"},
				{"entity","dao","service","service/impl","model/dto","model/request","model/request","model/request","controller"}};
		Map<String,CodeDTO> rootMap = new HashMap<String,CodeDTO>();
		rootMap.put("code", codeDTO);
		String key = UUID.randomUUID().toString();
		for(int i = 0;i<flts[0].length;i++) {
			try {
				FreemarkerUtils.createFile(flts[0][i], goldConstant.getFilePath()+File.separator+key+File.separator+flts[2][i]+File.separator+flts[1][i].replaceAll("Entity", codeDTO.getClassName()), rootMap);
			} catch (Exception e) {
				e.printStackTrace();
			}	
		}
		try {
			File f = new File(goldConstant.getFilePath()+File.separator+key);
			CompressUtil.compressFolder(goldConstant.getFilePath()+File.separator+key+".zip", f);
		} catch (ZipException e) {
			e.printStackTrace();
		}finally {
			File file = new File(goldConstant.getFilePath()+File.separator+key);
			file.delete();
		}
		return key;
	}

	
}
