package com.realnet.DynamicDashbard.controllers;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
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.DynamicDashbard.entities.ChartType;
import com.realnet.DynamicDashbard.services.ChartTypeService;

@RestController
@RequestMapping("/api/chart-types")
@CrossOrigin(origins = "*")
public class ChartTypeController {

	@Autowired
	private ChartTypeService chartTypeService;

	@GetMapping
	public List<ChartType> getAllChartTypes() {
		return chartTypeService.getAllChartTypes();
	}

	@GetMapping("/byname")
	public ResponseEntity<ChartType> getAllChartTypes(@RequestParam String chartName) {
		Optional<ChartType> chartType = chartTypeService.getChartTypeByName(chartName);

		if (!chartType.isPresent()) {
			System.out.println(" chart not found");

		}
		System.out.println(chartName + "  found :\n");

		return chartType.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
	}

	@GetMapping("/active")
	public List<ChartType> getActiveChartTypes() {
		return chartTypeService.getActiveChartTypes();
	}

	@GetMapping("/{id}")
	public ResponseEntity<ChartType> getChartTypeById(@PathVariable Long id) {
		Optional<ChartType> chartType = chartTypeService.getChartTypeById(id);
		return chartType.map(ResponseEntity::ok).orElse(ResponseEntity.notFound().build());
	}

	@PostMapping
	public ChartType createChartType(@RequestBody ChartType chartType) {
		return chartTypeService.saveChartType(chartType);
	}

	@PutMapping("/{id}")
	public ResponseEntity<ChartType> updateChartType(@PathVariable Long id, @RequestBody ChartType chartTypeDetails) {
		try {
			ChartType updatedChartType = chartTypeService.updateChartType(id, chartTypeDetails);
			return ResponseEntity.ok(updatedChartType);
		} catch (RuntimeException e) {
			return ResponseEntity.notFound().build();
		}
	}

	@DeleteMapping("/{id}")
	public ResponseEntity<Void> deleteChartType(@PathVariable Long id) {
		try {
			chartTypeService.deleteChartType(id);
			return ResponseEntity.ok().build();
		} catch (RuntimeException e) {
			return ResponseEntity.notFound().build();
		}
	}
}