package eu.dnetlib.dli.info;

import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.rmi.enabling.ISLookUpException;
import eu.dnetlib.rmi.enabling.ISLookUpService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by sandro on 3/3/17.
 */
@Controller
public class DLIInfoController {

    private static final Log log = LogFactory.getLog(DLIInfoController.class);

    @Autowired
    private UniqueServiceLocator serviceLocator;


    @RequestMapping(value = "/ui/dli/datasource/datasources.do")
    @ResponseBody
    public List<DLIDatasourceInfo> listDatasources(final ModelMap map) throws ISLookUpException {
        return dliDatasources();
    }

    private List<DLIDatasourceInfo> dliDatasources() throws ISLookUpException {

        final ISLookUpService service = serviceLocator.getService(ISLookUpService.class);

        final String xquery = "for $x in collection('/db/DRIVER/RepositoryServiceResources/RepositoryServiceResourceType') \n" +
                "return concat($x//OFFICIAL_NAME/text(), '<@>', $x//REPOSITORY_WEBPAGE/text(), '<@>',  $x//ICON_URI/text(), '<@>',$x//LONGITUDE/text(), '<@>',$x//LATITUDE/text(), '<@>', $x//FIELD[./key='NamespacePrefix']/value/text() )\n";
        List<String> result = service.quickSearchProfile(xquery);

        if (result != null) {
            final List<DLIDatasourceInfo> dliDatasources = result.stream()
                    .map(it -> it.split("<@>"))
                    .map(it -> new DLIDatasourceInfo(it[0], it[1], it[2], Double.parseDouble(it[3]), Double.parseDouble(it[4]), it[5]))
                    .collect(Collectors.toList());
            return dliDatasources;
        }
        return null;
    }


}
