package com.realnet.vpspack.Services;

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

import org.apache.bcel.generic.NEW;
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.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.itextpdf.text.pdf.PdfStructTreeController.returnType;
import com.realnet.Heplers.FileHelper;
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.Repository.SiteBuilderRepository;

@Service
public class SiteBuilderService {
	@Autowired
	private SiteBuilderRepository Repository;
	@Autowired
	private AppUserServiceImpl userService;
	@Autowired
	private RealmService realmService;

	@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<?> createHtmlFile(String siteBuilderName, Map<String, String> pageHtmlMap)
			throws IOException {

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

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

		String url = PortConstant.SUREOPS_NEW_DOMAIN + "/token/startContainer/182?folderName=" + siteBuilderName;

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

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

		}

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

	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;

	}

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