package it.enea.cruise.service.data;

import java.util.Map;

import it.enea.cruise.exceptions.TokenNotValidException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import it.enea.cruise.model.parametricQuery.ParametricQuery;
import it.enea.cruise.model.user.User;
import it.enea.cruise.service.idp.IdpProvider;
import it.enea.cruise.service.parametricQuery.LocalQueryParameterInterface;
import it.enea.cruise.service.parametricQuery.ParametricQueryInterface;
import it.enea.cruise.service.parametricQuery.ParametricQueryManager;
import it.enea.cruise.service.parametricQuery.ParametricQueryManager.ResultWithMetadata;
import it.enea.cruise.repositories.UserRepository;
import lombok.extern.log4j.Log4j2;

import javax.transaction.Transactional;


@Service
@Log4j2
public class DataService implements IDataService {
    @Autowired
    LocalQueryParameterInterface lqpInterface;

    @Autowired
    UserRepository userInterface;


    @Autowired
    ParametricQueryInterface pqueryInterface;


    @Autowired
    ParametricQueryManager pqm;

    @Autowired
    IdpProvider idpClientManager;

    @Override
    @Transactional
    public ResultWithMetadata getData(
            Map<String, String> inputData,
            String token,
            String language) {

        log.info("Input data:" + inputData.toString());
        if (idpClientManager.isValid(token)) {

            User userdto = idpClientManager.getUserByToken(token);

            User user = userInterface.findBySubject(userdto.getUuid());

            inputData.put("userid", user.getUserid().toString());

            ParametricQuery pq = pqueryInterface.findByQueryid(new Long(inputData.get("queryid")));
            return pqm.executeQuery(pq, inputData, language);
        }

        log.info("Warning: token is not valid");
        throw new TokenNotValidException("Token is not valid");
    }

}

