package com.realnet.vpspack.Services;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
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.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.realnet.Heplers.FileHelper;
import com.realnet.OpenAi.Services.SureopsService;
import com.realnet.fnd.response.EntityResponse;
import com.realnet.realm.Entity.Realm;
import com.realnet.realm.Services.RealmService;
import com.realnet.users.entity1.AppUser;
import com.realnet.users.service1.AppUserServiceImpl;
import com.realnet.utils.PortConstant;
import com.realnet.utils.RealNetUtils;
import com.realnet.vpspack.Entity.SiteBuilder;
import com.realnet.vpspack.Entity.SiteBuilderDto;
import com.realnet.vpspack.Repository.SiteBuilderRepository;

@Service
public class SiteBuilderService {

	@Autowired
	private SiteBuilderRepository Repository;

	@Autowired
	private AppUserServiceImpl userService;

	@Autowired
	private RealmService realmService;

	@Autowired
	private SureopsService sureopsService;

	@Autowired
	private FileHelper fileHelper;

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

	public SiteBuilder Savedata(SiteBuilder data) {

		data.setUpdatedBy(getUser().getUserId());
		data.setCreatedBy(getUser().getUserId());
		data.setAccountId(getUser().getAccount().getAccount_id());
		SiteBuilder save = Repository.save(data);
		return save;
	}

//	get all with pagination
	public Page<SiteBuilder> getAllWithPagination(Pageable page) {
		return Repository.findAll(page, getUser().getUserId());
	}

	public List<SiteBuilder> getdetails() {
		List<Realm> realm = realmService.findByUserId(getUser().getUserId());
		List<SiteBuilder> all = Repository.findAll(getUser().getUserId());

		return all;
	}

	public SiteBuilder getdetailsbyId(Integer id) {
		return Repository.findById(id).get();
	}

	public void delete_by_id(Integer id) {
		Repository.deleteById(id);
	}

	public SiteBuilder update(SiteBuilder data, Integer id) {
		SiteBuilder old = Repository.findById(id).get();

		if (data.getName() != null) {
			old.setName(data.getName());
		}

		if (data.getDescription() != null) {
			old.setDescription(data.getDescription());
		}

		if (data.getModel() != null) {
			old.setModel(data.getModel());
		}

		// isActive is boolean, use Boolean wrapper to check null safety
		if (data.isActive() != old.isActive()) {
			old.setActive(data.isActive());
		}

		if (data.getPrompt() != null) {
			old.setPrompt(data.getPrompt());
		}

		old.setUpdatedBy(getUser().getUserId());

		final SiteBuilder test = Repository.save(old);
		return test;
	}

	public ResponseEntity<?> create(Integer siteId, String siteBuilderName, SiteBuilderDto dto) throws IOException {

		Map<String, String> pageHtmlMap = dto.getPageHtmlMap();

		siteBuilderName = RealNetUtils.formatStringtoSql(siteBuilderName).toLowerCase();
		String folderPath = projectPath + File.separator + "Files" + File.separator + siteBuilderName;
		int i = 0;

		String cssFileName = "style.css";

		fileHelper.createFile(folderPath, cssFileName.toLowerCase(), dto.getCss());

		String startindex = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" + "  <title>Welcome</title>\n" + ""
				+ "<!-- CSS file link -->\r\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();

			htmlContent = htmlContent.replaceAll("(?is)<style[^>]*>.*?</style>",
					"<link rel=\"stylesheet\" href=\"style.css\" />");

			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 ");
		}

		return new ResponseEntity<>(new EntityResponse(i + " files created  "), HttpStatus.CREATED);
	}

	public void deploy(Integer siteId, String siteBuilderName) {

		Long serverPortNo = sureopsService.getUpdatedPort(1L);
		String url = PortConstant.SUREOPS_NEW_DOMAIN + "/token/startContainer/182?folderName=" + siteBuilderName
				+ "&serverPortNo=" + serverPortNo;

		ResponseEntity<Object> get = POST(url);
		if (get.getStatusCodeValue() < 209) {
			System.out.println(" deplpoyed also...");

			String deployedUrl = PortConstant.DOMAIN + ":" + serverPortNo;
			SiteBuilder siteBuilder = getdetailsbyId(siteId);
			siteBuilder.setDeployedUrl(deployedUrl);

			SiteBuilder savedata = Savedata(siteBuilder);

			System.out.println(" deployed url updated...");

		} else {
			System.out.println("not  deplpoyed ");

		}

	}

	public AppUser getUser() {
		AppUser user = userService.getLoggedInUser();
		return user;

	}

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

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

		return u;

	}

	public ResponseEntity<Object> POST(String jobinfo) {
		HashMap<Object, Object> user = new HashMap<>();
		RestTemplate restTemplate = new RestTemplate();
		String resourceUrl = jobinfo;
		HttpHeaders headers = getHeaders();
		HttpEntity<Object> request = new HttpEntity<Object>(user, headers);
		ResponseEntity<Object> res = restTemplate.postForEntity(resourceUrl, request, Object.class);

		return res;

	}

	private HttpHeaders getHeaders() {
		HttpHeaders headers = new HttpHeaders();
		headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
		headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
		return headers;
	}
}
