package com.example.demo.service.impl;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.common.APIResponse;
import com.example.demo.dto.AdunitDealDTO;
import com.example.demo.dto.AdunitDealListDTO;
import com.example.demo.dto.DealResponseDTO;
import com.example.demo.entity.AdunitDeal;
import com.example.demo.entity.Configurations;
import com.example.demo.entity.Deal;
import com.example.demo.repository.AdunitDealRepository;
import com.example.demo.repository.ConfigurationRepo;
import com.example.demo.repository.DealRepository;
import com.example.demo.service.AdunitDealService;

import redis.clients.jedis.Jedis;

@Service
public class AdunitDealServiceImpl implements AdunitDealService{

	@Autowired
	private AdunitDealRepository repo;
	
	@Autowired
	private Jedis jedis;
	
	@Autowired
	private DealRepository dealrepo;
	
	@Autowired
	private ConfigurationRepo configrepo;

    @Override
	public APIResponse createlink(AdunitDealDTO create) {
		APIResponse api = new APIResponse();
		
		AdunitDeal adudeal = new AdunitDeal();
		adudeal.setAdunit_id(create.getAdunit_id());
		adudeal.setDeal_id(create.getDeal_id());
		repo.save(adudeal);
		
		String key = "Adunit_Deal" + adudeal.getAdunit_id();
		List<AdunitDeal> dealList = repo.findbyadunitid(adudeal.getAdunit_id());
		List<UUID> camapaignidlist = dealList.stream().map(id -> id.getDeal_id()).collect(Collectors.toList());
		JSONArray ja = new JSONArray();
		for (UUID id : camapaignidlist) {
			JSONObject obj = new JSONObject();
			obj.put("deal_id", id.toString());
			ja.add(obj);
		}
		Map<String, String> map = new HashMap<>();
		map.put("connecteddeal", ja.toString());
		jedis.hmset(key, map);

		api.setData(adudeal);
		api.setMessage("Adunit_Deal_Linked_Successfully");
		api.setMsgCode("ADUNIT_DEAL_LINKED_SUCCESSFULLY");
		return api;
	}

	@Override
	public APIResponse deletelink(AdunitDealDTO delete) {
		APIResponse api = new APIResponse();
		
		AdunitDeal deal = repo.findbyadunitanddeal(delete.getAdunit_id(),delete.getDeal_id());
		repo.delete(deal);
		
		String key ="Adunit_Deal_"+delete.getAdunit_id();
		jedis.del(key);
		
		List<AdunitDeal> dealList = repo.findbyadunitid(delete.getAdunit_id());
		List<UUID> camapaignidlist = dealList.stream().map(id -> id.getDeal_id()).collect(Collectors.toList());
		JSONArray ja = new JSONArray();
		for (UUID id : camapaignidlist) {
			JSONObject obj = new JSONObject();
			obj.put("deal_id", id.toString());
			ja.add(obj);
		}
		Map<String, String> map = new HashMap<>();
		map.put("connecteddeal", ja.toString());
		jedis.hmset(key, map);

		api.setData(delete);
		api.setMessage("Adunit_Deal_UnLinked_Successfully");
		api.setMsgCode("ADUNIT_DEAL_UNLINKED_SUCCESSFULLY");
		
		return api;
	}

	@Override
	public APIResponse list(AdunitDealListDTO list) {
		APIResponse api = new APIResponse();
		List<AdunitDeal> adudeal = repo.findbyadunitid(list.getAdunit_id());
		List<DealResponseDTO> response = adudeal.stream().map(id->MapToDTO(id.getDeal_id())).collect(Collectors.toList());
		api.setData(response);
		api.setMessage("Deal_List_Get_Successfully");
		api.setMsgCode("DEAL_LIST_GET_SUCCESSFULLY");
		return api;
	}
	
	private DealResponseDTO MapToDTO(UUID deal_id) {
		DealResponseDTO response = new DealResponseDTO();
		
		Deal deal = dealrepo.findById(deal_id).orElse(null);
        response.setDeal_id(deal.getDeal_id());
        response.setBidfloor(deal.getBidfloor());
        response.setIncluding_seats(deal.getIncluding_seats());
        response.setDeal_name(deal.getName());
        response.setKeywords(deal.getKeywords());
		
        List<Configurations> allObj = configrepo.findAll();
		Configurations config = allObj.get(0);
		DateTimeFormatter newYorkDateFormatter = DateTimeFormatter.ofPattern(config.getConfigValue());
		String arr = newYorkDateFormatter.format(ZonedDateTime.of(deal.getCreated_at(), ZoneId.of("UTC-4")));
        response.setCreated_at(arr);
        response.setCreated_by(deal.getCreated_by());
        
		String arr1 = newYorkDateFormatter.format(ZonedDateTime.of(deal.getUpdated_at(), ZoneId.of("UTC-4")));
        response.setUpdated_at(arr1);
        response.setUpdated_by(deal.getUpdated_by()); 
        
        if(deal.getDeleted_at()!=null) {
    	 String arr2 = newYorkDateFormatter.format(ZonedDateTime.of(deal.getDeleted_at(), ZoneId.of("UTC-4")));
         response.setDeleted_at(arr2);
        }
        response.setIs_deleted(deal.getIs_deleted());
        response.setDeleted_by(deal.getDeleted_by());
        
		return response;
	}

}
