package com.example.controller;

import com.example.baidu.ueditor.ActionEnter;
import com.example.baidu.ueditor.ConfigManager;
import com.example.util.AliyunOSSConfigConstant;
import com.example.util.AliyunOSSUtil;
import com.example.util.DataConfig;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller

public class UEditorController {

	private Map<String, AliyunOSSConfigConstant> projectMap = new HashMap<String, AliyunOSSConfigConstant>();
	
	
	@Autowired
	private AliyunOSSUtil aliyunOSSUtil;
	

	
    @RequestMapping("/")
    private String showPage() {
        return "index";
    }

    @RequestMapping(value = "/config")
    public void config(HttpServletRequest request, HttpServletResponse response) {
    	
    	String env=request.getParameter("env");
    	
    	
    	AliyunOSSConfigConstant aliyunOSSConfigConstant=aliyunOSSUtil.getOssConfig(env);
    	
    	//OSSConfigConstant oSSConfigConstant=ev.getProperty("projectMap.woyou", OSSConfigConstant.class);
        response.setContentType("application/json");
        String rootPath = request.getSession().getServletContext().getRealPath("/");
        try {
        	ConfigManager configManger=ConfigManager.getInstance(rootPath, request.getContextPath(), request.getRequestURI());
        	String imageUrlPrefix=(String) configManger.getAllConfig().get("imageUrlPrefix");
        	
        	
            String exec = new ActionEnter(request, rootPath).exec();
            //exec=exec.replace("\"imageUrlPrefix\":\"https://imgb.mofangx.com/\"","'imageUrlPrefix':'"+imageUrlPrefix+"'");
            exec=exec.replace("{imgUrl}",aliyunOSSConfigConstant.getHost()+"/");
            exec=exec.replace("{basePath}",aliyunOSSConfigConstant.getFolder());
            
            //exec=exec.replace("'basePath':'erp/'","'basePath':'"+ossPath+"'");

            System.out.println("exec:"+exec);
        	/*if(!exec.contains("videoMaxSize")) {
        		 JSONObject jsonConfig =new JSONObject(exec);
                jsonConfig.put("url", imageUrl+jsonConfig.getString("url"));
                System.out.println(jsonConfig);
                exec=jsonConfig.toString();
        	}*/
            
           
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }
}
