package de.oaa.xxx.games.chastity.ttlock;

import java.util.Collections;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;

@Service
public class TTLockService {

	private final RestTemplate restTemplate;

	private static final String UNLOCK_CODE_NAME = "xxx-unlock-code";

	public TTLockService() {
		restTemplate = new RestTemplate();

	}

	public TTLockDetailResponse getLockDetail(String clientId, String accessToken, int lockId) {
		String url = UriComponentsBuilder.fromUriString("https://euapi.ttlock.com/v3/lock/detail")
				.queryParam("clientId", clientId).queryParam("accessToken", accessToken).queryParam("lockId", lockId)
				.queryParam("date", System.currentTimeMillis()).toUriString();

		try {
			HttpHeaders headers = new HttpHeaders();
			headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
			TTLockDetailResponse response = restTemplate.getForObject(url, TTLockDetailResponse.class);
			System.out.println(response);
			return response;
		} catch (Exception e) {
			System.err.println("Fehler beim Abrufen der Details: " + e.getMessage());
			return null;
		}
	}

	public Integer addCustomPasscode(String clientId, String accessToken, int lockId, String pin) {

		String url = "https://euapi.ttlock.com/v3/keyboardPwd/add";

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
		map.add("clientId", clientId);
		map.add("accessToken", accessToken);
		map.add("lockId", String.valueOf(lockId));
		map.add("keyboardPwd", pin); // Der 4-9 stellige PIN
		map.add("keyboardPwdName", UNLOCK_CODE_NAME);
		map.add("addType", "2");
		map.add("keyboardPwdType", "2");
		map.add("date", String.valueOf(System.currentTimeMillis()));

		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

		try {
			ResponseEntity<TTLockAddPasscodeResponse> response = restTemplate.postForEntity(url, request,
					TTLockAddPasscodeResponse.class);
			if (response.getBody() != null && response.getBody().isSuccess()) {
				return response.getBody().getKeyboardPwdId();
			} else {
				System.out.println("Fehler von TTLock: " + response.getBody().getErrmsg());
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public String deleteCustomPasscode(String clientId, String accessToken, int lockId, int keyboardPwdId) {
		String url = "https://euapi.ttlock.com/v3/keyboardPwd/delete";

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

		MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
		map.add("clientId", clientId);
		map.add("accessToken", accessToken);
		map.add("lockId", String.valueOf(lockId));
		map.add("keyboardPwdId", String.valueOf(keyboardPwdId));
		map.add("deleteType", "2");
		map.add("date", String.valueOf(System.currentTimeMillis()));

		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

		try {
			ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
			return response.getBody();
		} catch (Exception e) {
			return "{\"errcode\":-1, \"errmsg\":\"" + e.getMessage() + "\"}";
		}
	}

	public void findAndDeleteLocksByName(String clientId, String accessToken, int lockId) {
		ObjectMapper mapper = new ObjectMapper();

		String listUrl = UriComponentsBuilder.fromUriString("https://euapi.ttlock.com/v3/lock/listKeyboardPwd")
				.queryParam("clientId", clientId)
				.queryParam("accessToken", accessToken)
				.queryParam("lockId", lockId)
				.queryParam("pageNo", 1)
				.queryParam("pageSize", 100)
				.queryParam("date", System.currentTimeMillis()).toUriString();

		try {
			String response = restTemplate.getForObject(listUrl, String.class);
			JsonNode root = mapper.readTree(response);
			JsonNode list = root.get("list");

			if (list != null && list.isArray()) {
				for (JsonNode unlockcode : list) {
					String name = unlockcode.get("keyboardPwdName").asText();
					int passwordId = unlockcode.get("keyboardPwdId").asInt();

					if (name.equalsIgnoreCase(UNLOCK_CODE_NAME)) {
						deleteCustomPasscode(clientId, accessToken, lockId, passwordId);
					}
				}
			}
		} catch (Exception e) {
			System.err.println("Fehler beim Massenlöschen: " + e.getMessage());
		}
	}

	@JsonIgnoreProperties(ignoreUnknown = true)
	@Getter
	@Setter
	@Data
	public static class TTLockDetailResponse {
		private int errcode;
		private String errmsg;
		private String lockName;
		private String lockAlias;
		private int lockId;
		private int electricQuantity;
		private String modelNum;
		private String featureValue;
		private String adminPwd;
		private String state;
	}

	@Data
	@JsonIgnoreProperties(ignoreUnknown = true)
	public static class TTLockAddPasscodeResponse {
		private int errcode;
		private String errmsg;
		private Integer keyboardPwdId; // Die ID des neuen Pins in der Cloud

		public boolean isSuccess() {
			return errcode == 0;
		}
	}
}
