package Service.Season_service;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import configuration.MQConfig;
import models.Competition;
import models.Event;
import models.Match_Event;
import models.Season;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/Seasons")
public class SeasonController {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    RestTemplate restTemplate;
    List<Season> seasons = new ArrayList<>() {{
        add(new Season(1, "2021", "2022"));
        add(new Season(2, "2022", "2023"));
        add(new Season(3, "2023", "2034"));
    }};

    @RequestMapping("/GetSeasonsStanding/{CompetitionName}")
    public Competition getHistoryEventOfCompetition(@PathVariable("CompetitionName") String competitionName) throws JsonProcessingException {
        Competition competition = new Competition();
        competition.setName(competitionName);
        List<Season> seasonResult = new ArrayList<>();
        for (Season s : seasons) {
            Season season = new Season(s.getId(), s.getStartYear(), s.getFinishYear());
            Event resultPart1 = restTemplate.getForObject("https://www.thesportsdb.com/api/v1/json/3/searchfilename.php?e=" + competitionName + "_" + s.getStartYear(), Event.class);
            Event resultPart2 = restTemplate.getForObject("https://www.thesportsdb.com/api/v1/json/3/searchfilename.php?e=" + competitionName + "_" + s.getFinishYear(), Event.class);
            season.getMatch_events().addAll(resultPart1.getEvent());
            season.getMatch_events().addAll(resultPart2.getEvent());
//            String result = restTemplate.getForObject("https://www.thesportsdb.com/api/v1/json/3/searchfilename.php?e=" + competitionName + "_" + s.getStartYear(), String.class);
//            ObjectMapper objectMapper = new ObjectMapper();
//             //Parse the JSON array
//            JsonNode jsonNode = objectMapper.readTree(result);
//            // Create a list to store the Match_Event objects
//            List<Match_Event> matchEvents = new ArrayList<>();
            // Iterate over the JSON array and create Match_Event objects
//            for (JsonNode node1 : jsonNode) {
//                for (JsonNode node : node1) {
//                    Match_Event matchEvent = new Match_Event();
//                    matchEvent.setIdEvent(node.get("idEvent").asText());
//                    matchEvent.setStrEvent(node.get("strEvent").asText());
//                    matchEvent.setDateEvent(node.get("dateEvent").asText());
//                    matchEvent.setStrLeague(node.get("strLeague").asText());
//                    matchEvent.setStrHomeTeam(node.get("strHomeTeam").asText());
//                    matchEvent.setStrAwayTeam(node.get("strAwayTeam").asText());
//                    matchEvent.setIntAwayScore(node.get("intHomeScore").asInt());
//                    matchEvent.setIntAwayScore(node.get("intAwayScore").asInt());
//                    matchEvents.add(matchEvent);
            seasonResult.add(season);
        }
              //  season.getMatch_events().addAll(matchEvents);
            //}
            //seasonResult.add(season);
        //}
        Competition response = new Competition();
        response.setSeasonList(seasonResult);
        response.setName(competitionName);
        return response;
    }

    private static final Logger LOGGER = LoggerFactory.getLogger(SeasonController.class);
    @RabbitListener(queues = MQConfig.SeasonInfoRespQueue)
    public void respCompetition(String competitionName){

        LOGGER.info(String.format("Received CompetitionName: %s", competitionName));

        Competition competition = new Competition();
        competition.setName(competitionName);
        List<Season> seasonResult = new ArrayList<>();
        for (Season s : seasons) {
            Season season = new Season(s.getId(), s.getStartYear(), s.getFinishYear());
            Event resultPart1 = restTemplate.getForObject("https://www.thesportsdb.com/api/v1/json/3/searchfilename.php?e=" + competitionName + "_" + s.getStartYear(), Event.class);
            Event resultPart2 = restTemplate.getForObject("https://www.thesportsdb.com/api/v1/json/3/searchfilename.php?e=" + competitionName + "_" + s.getFinishYear(), Event.class);
            season.getMatch_events().addAll(resultPart1.getEvent());
            season.getMatch_events().addAll(resultPart2.getEvent());
//            String result = restTemplate.getForObject("https://www.thesportsdb.com/api/v1/json/3/searchfilename.php?e=" + competitionName + "_" + s.getStartYear(), String.class);
//            ObjectMapper objectMapper = new ObjectMapper();
//             //Parse the JSON array
//            JsonNode jsonNode = objectMapper.readTree(result);
//            // Create a list to store the Match_Event objects
//            List<Match_Event> matchEvents = new ArrayList<>();
            // Iterate over the JSON array and create Match_Event objects
//            for (JsonNode node1 : jsonNode) {
//                for (JsonNode node : node1) {
//                    Match_Event matchEvent = new Match_Event();
//                    matchEvent.setIdEvent(node.get("idEvent").asText());
//                    matchEvent.setStrEvent(node.get("strEvent").asText());
//                    matchEvent.setDateEvent(node.get("dateEvent").asText());
//                    matchEvent.setStrLeague(node.get("strLeague").asText());
//                    matchEvent.setStrHomeTeam(node.get("strHomeTeam").asText());
//                    matchEvent.setStrAwayTeam(node.get("strAwayTeam").asText());
//                    matchEvent.setIntAwayScore(node.get("intHomeScore").asInt());
//                    matchEvent.setIntAwayScore(node.get("intAwayScore").asInt());
//                    matchEvents.add(matchEvent);
            seasonResult.add(season);
        }
        //  season.getMatch_events().addAll(matchEvents);
        //}
        //seasonResult.add(season);
        //}
        Competition response = new Competition();
        response.setSeasonList(seasonResult);
        response.setName(competitionName);
        rabbitTemplate.convertAndSend(MQConfig.EXCHANGE,MQConfig.SEA_RES_ROUTING_KEY,response);


        log.info(String.format("Queued: Movie with id %s",response.getId()));
    }

}

