package eu.dnetlib.efg.thumbnails;

import eu.dnetlib.data.objectstore.connector.ObjectStore;
import eu.dnetlib.data.objectstore.gridFS.GridFSObjectStore;
import eu.dnetlib.data.objectstore.gridFS.GridFSObjectstoreDaoImpl;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;
import eu.dnetlib.miscutils.collections.Pair;
import eu.dnetlib.rmi.data.ObjectStoreFile;
import eu.dnetlib.rmi.enabling.ISLookUpService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by sandro on 4/12/17.
 */
@Controller
public class ThumbnailController {


    @Autowired
    UniqueServiceLocator serviceLocator;

    @Autowired
    GridFSObjectstoreDaoImpl objectstoreDao;


    private Map<String, String> objectStoresThumbnail;


    @RequestMapping(value = "/thumbnail/objectStoresThumbnail")
    @ResponseBody
    public Map<String, String> getObjectStoresThumbnail(ModelMap map) throws Exception {
        if (objectStoresThumbnail == null) {
            createObjectStoreThumbnail();
        }
        return objectStoresThumbnail;
    }


    @RequestMapping(value = "/thumbnail/getThumbnail/{type}/{size}/{metadataId}", method= RequestMethod.GET)
    public void getThumbnail(final HttpServletResponse response, @PathVariable final String metadataId,
                             @PathVariable final int size, @PathVariable  String type) throws Exception {
        if (size != 96 && size != 250) throw new Exception("Image size not supported!");
        InputStream inputStream = null;
        if(!type.equalsIgnoreCase("video") && !type.equalsIgnoreCase("image") && !type.equalsIgnoreCase("text")){
            type = "video";
        }
        if (objectStoresThumbnail == null) {
            createObjectStoreThumbnail();
        }

        if (objectStoresThumbnail.size() == 0){
            inputStream = getClass().getResourceAsStream(String.format("/eu/dnetlib/thumbnail/NF%s_%d.jpg", type.toLowerCase(), size));
        }else{
            final GridFSObjectStore objectStore = (GridFSObjectStore) objectstoreDao.getObjectStore(objectStoresThumbnail.get(String.format("thumb%d", size == 250 ? 256 : size)));

            final ObjectStoreFile objectStoreFile = objectStore.deliverObjectFromMetadataIdentifier(metadataId);

            if (objectStoreFile == null) {
                inputStream = getClass().getResourceAsStream(String.format("/eu/dnetlib/thumbnail/NF%s_%d.jpg", type.toLowerCase(), size));
            } else {
                inputStream = objectStore.deliverStream(objectStoreFile.getObjectID());
            }
        }

        if (inputStream != null) {
            try {
                final ServletOutputStream outputStream = response.getOutputStream();
                IOUtils.copy(inputStream, outputStream);
            } finally {
                inputStream.close();
            }
        }
    }


    private void createObjectStoreThumbnail() throws Exception {
        final String query = "for $x in collection('/db/DRIVER/ObjectStoreDSResources/ObjectStoreDSResourceType')\n" +
                "where  $x//OBJECTSTORE_INTERPRETATION = 'thumb96' or $x//OBJECTSTORE_INTERPRETATION = 'thumb256' \n" +
                " return concat($x//OBJECTSTORE_INTERPRETATION, '<-->',   $x//RESOURCE_IDENTIFIER/@value/string())";
        final ISLookUpService lookUpService = serviceLocator.getService(ISLookUpService.class);
        final List<String> queryResult = lookUpService.quickSearchProfile(query);
        if (queryResult == null) {
            throw new Exception("Missing objectStore Thumbnail");
        }
        objectStoresThumbnail = new HashMap<>();
        queryResult.stream().forEach(item -> {
            final String[] splitString = item.split("<-->");
            if (splitString == null || splitString.length != 2)
                throw new RuntimeException("Error wrong splitting");
            objectStoresThumbnail.put(splitString[0], splitString[1]);

        });



    }

}
