package com.realnet.OpenAi.Services;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.realnet.Heplers.FileHelper;
import com.realnet.utils.PortConstant;

@Service
public class SureopsService {

	@Value("${projectPath}")
	private String projectPath;

	@Autowired
	private FileHelper fileHelper;

	@Autowired
	private Script_Making script_serviceMaking;

	public void createHtmlFiles(Integer projId, Map<String, String> pageHtmlMap) throws IOException {

		String prj_url = PortConstant.BACKEND_PORTAL_DOMAIN + "/token/fnd1/callingsureops/getproject/" + projId;

		// get project
		ResponseEntity<Object> prj = GET(prj_url);
		Object prj_body = prj.getBody();
		List<String> list = script_serviceMaking.callforproject(prj_body);

		String PRJ_NAME = list.get(0);

		String folderPath = projectPath + File.separator + projId + File.separator + "index" + File.separator
				+ PRJ_NAME;
		int i = 0;

//		String index = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "  <title>Welcome</title>\n" + "</head>\n"
//				+ "<body>\n" + "  <h1>Welcome to the Web App</h1>\n" + "  <ul>\n"
//				+ "    <li><a href=\"home.html\">Home Page</a></li>\n" + "  </ul>\n" + "</body>\n" + "</html>";

//		String filename = "index.html";
//		fileHelper.createFile(folderPath, filename, index);

		String startindex = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "  <title>Welcome</title>\n" + "</head>\n"
				+ "<body>\n";

		String endindex = "</body>\n" + "</html>";

		for (Map.Entry<String, String> entry : pageHtmlMap.entrySet()) {

			String pageName = entry.getKey().trim().replaceAll("\\s+", "_") + ".html"; // remove spaces from name
			String htmlContent = entry.getValue();

			if (pageName.equalsIgnoreCase("home.html")) {

				pageName = "index.html";

				htmlContent = startindex + " \n" + htmlContent + endindex;

			}

			fileHelper.createFile(folderPath, pageName.toLowerCase(), htmlContent);
			i++;
			System.out.println(i + " file created ");
		}
	}

	public Long getUpdatedPort(Long webid) {

		String url = PortConstant.SUREOPS_DOMAIN + "/sureops/resource/port";

		ResponseEntity<Object> get = GET(url);

		Object body = get.getBody();
		Long port = Long.valueOf(body.toString());
		return port;

	}

	public ResponseEntity<Object> GET(String get) {
		RestTemplate restTemplate = new RestTemplate();

		ResponseEntity<Object> u = restTemplate.getForEntity(get, Object.class);

		return u;

	}

}
