 CONFIG = require '../config'
 Async  = require 'async'
 log = require('../log')(module)
+Accepts    = require 'accepts'
 
 _denoise_id = (s) ->
 	sold = s
 	s = s.replace(/doi:/i, '')
 	s = s.replace(new RegExp("https?://(dx\\.)?doi.org/?"), '')
-	log.debug("_denoise_id: #{sold} -> #{s}")
+	# log.debug("_denoise_id: #{sold} -> #{s}")
 	return s
 
 _get_id = (s) ->
 	snew = s.substr(s.lastIndexOf('/') + 1)
-	log.debug("_get_id: #{s} -> #{snew}")
+	# log.debug("_get_id: #{s} -> #{snew}")
 	return snew
 
 #publication -> entityLink -> dataset

module.exports = (app, done) ->
	{Entity, EntityLink} = app.schemo.models

	_find_links_from_publication = (fromEntity, cb) ->
		FOUND_LINKS = []
		#
		# publication -> LINKPC
		#
		EntityLink.find({fromEntity: fromEntity.uri()}).limit(100).exec (err, links1) ->
			return cb err if err
			Async.eachSeries links1, (link, cbLinks1) ->
				#
				# LINKPC -> citedData
				#
				Entity.findOne {_id: _get_id link.toEntity}, (err, citedData) ->
					return cbLinks1 err if err or not citedData
					# TODO same_as
					# TODO same_as
					# TODO same_as
					#
					# citedData -> LINKCD
					#
					EntityLink.findOne {fromEntity: citedData.uri()}, (err, link2) ->
						return cbLinks1 err if err or not link2
						#
						# LINKCD -> dataset
						#
						Entity.findOne {_id: _get_id link2.toEntity}, (err, toEntity) ->
							return cbLinks1 err if err or not toEntity
							# jsonify and replace fromEntity/toEntity with populated documents
							toPush = link2.toJSON()
							toPush.fromEntity = fromEntity.toJSON()
							toPush.toEntity = toEntity.toJSON()
							FOUND_LINKS.push toPush

				return cb err if err
				return cb null, FOUND_LINKS

	_find_links = (needleQuery, limit, cb) ->
		log.debug("Entity query:". needleQuery)
		FOUND_LINKS = []
		Entity.find(needleQuery).limit(limit).exec (err, entities) ->
			return cb err if err
			return cb null, [] if entities.length == 0
			Async.eachSeries entities, (needleEntity, cbEntities1) ->
				#
				# Query1 (publication -> dataset)
				#
				# log.debug "needleEntity", needleEntity.uri()
				if needleEntity.entityType is 'publication'
					_find_links_from_publication needleEntity, limit, (err, links) ->
						return cbEntities1 err if err
						FOUND_LINKS.push x for x in links
						return cbEntities1()
				else
					_find_links_to_dataset needleEntity, limit, (err, links) ->
						return cbEntities1 err if err
						FOUND_LINKS.push x for x in links
						return cbEntities1()
