package com.realnet.vpspack.Controllers;

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

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.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.realnet.Heplers.FileHelper;
import com.realnet.OpenAi.Services.SureopsService;
import com.realnet.fnd.response.EntityResponse;
import com.realnet.vpspack.Entity.SiteBuilder;
import com.realnet.vpspack.Entity.SiteBuilderDto;
import com.realnet.vpspack.Services.SiteBuilderService;
import org.eclipse.jgit.api.Git;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.io.FileUtils;

import java.io.File;

@RequestMapping(value = "/SiteTree")
@CrossOrigin("*")
@RestController
public class SiteBuilderController {

	@Autowired
	private SiteBuilderService Service;

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

	@Autowired
	private FileHelper fileHelper;

	@Autowired
	private SureopsService sureopsService;

	@PostMapping("/SiteTree")
	public SiteBuilder Savedata(@RequestBody SiteBuilder data) {
		SiteBuilder save = Service.Savedata(data);

		System.out.println("data saved..." + save);

		return save;
	}

	@PutMapping("/SiteTree/{id}")
	public SiteBuilder update(@RequestBody SiteBuilder data, @PathVariable Integer id) {
		SiteBuilder update = Service.update(data, id);
		System.out.println("data update..." + update);
		return update;
	}

//	get all with pagination
	@GetMapping("/SiteTree/getall/page")
	public Page<SiteBuilder> getall(@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "size", required = false) Integer size) {
		Pageable paging = PageRequest.of(page, size);
		Page<SiteBuilder> get = Service.getAllWithPagination(paging);

		return get;

	}

	@GetMapping("/SiteTree")
	public List<SiteBuilder> getdetails() {
		List<SiteBuilder> get = Service.getdetails();
		return get;
	}
// get all without authentication 

	@GetMapping("/token/SiteTree")
	public List<SiteBuilder> getallwioutsec() {
		List<SiteBuilder> get = Service.getdetails();
		return get;
	}

	@GetMapping("/SiteTree/{id}")
	public SiteBuilder getdetailsbyId(@PathVariable Integer id) {
		SiteBuilder get = Service.getdetailsbyId(id);
		return get;
	}

	@DeleteMapping("/SiteTree/{id}")
	public ResponseEntity<?> delete_by_id(@PathVariable Integer id) {
		Service.delete_by_id(id);
		return new ResponseEntity<>(new EntityResponse("Deleted"), HttpStatus.OK);

	}

	@PostMapping("/SiteTree/deploy")
	public ResponseEntity<?> createAndDeploy(@RequestParam Integer siteId, @RequestParam String siteBuilderName,
			@RequestBody SiteBuilderDto dto) throws IOException {

		ResponseEntity<?> htmlFile = Service.create(siteId, siteBuilderName, dto);

		Service.deploy(siteId, siteBuilderName);
		return htmlFile;

	}


    private static final String BASE_CLONE_PATH = "C:/cloned-repos"; // Change as needed

    @PostMapping("/clone")
    public ResponseEntity<String> cloneRepo(@RequestParam String gitUrl, @RequestParam String branch) {
        try {
            String repoName = gitUrl.substring(gitUrl.lastIndexOf("/") + 1).replace(".git", "");
            File localPath = new File(BASE_CLONE_PATH + File.separator + repoName);

            // Clean if already exists
            if (localPath.exists()) {
                FileUtils.deleteDirectory(localPath);
            }

            // Clone the specific branch
            Git.cloneRepository()
                .setURI(gitUrl)
                .setBranch(branch)
                .setDirectory(localPath)
                .call();

            return ResponseEntity.ok("Repository cloned successfully to: " + localPath.getAbsolutePath());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Failed to clone repository: " + e.getMessage());
        }
    }


//	it created all file of pages
	@PostMapping("/SiteTree/createFile")
	public ResponseEntity<?> createHtmlFiles(@RequestParam Integer siteId, @RequestParam String siteBuilderName,
			@RequestBody SiteBuilderDto dto) throws IOException {
		ResponseEntity<?> htmlFile = Service.create(siteId, siteBuilderName, dto);
		return htmlFile;
	}

	@GetMapping("/SiteTree/read")
	public ResponseEntity<?> readFile(@RequestParam String siteBuilderName, @RequestParam String filename) {

		String filepath = projectPath + File.separator + "Files" + File.separator + siteBuilderName;

		if (filename.equalsIgnoreCase("home")) {

			filename = "index";

		}
		ResponseEntity<?> file = fileHelper.readFile(filepath, filename);
		return file;
	}

}