import java.util.concurrent.*
import java.util.zip.ZipFile

interface EmojiConstants {
	def HEX_CODEPOINT_END_POSITION = 43
	def STATUS_END_POSITION = 65
	def EMOJI_POSITION = 67
}

class UiEntryCreator implements EmojiConstants {
	
	static def createUiEntryFile(File emojiDirectory, File emojiGraphicsJarFile){
		
		new ZipFile(emojiGraphicsJarFile).withCloseable{ graphicsJar ->
		
			Node root = new Node(null, 'FreeplaneEmojiEntries')
			Node group = null 
			Node subgroup = null
	 		Node action = null
			Node variantSubgroup = null
			boolean firstInGroupSet = false
			boolean firstInSubgroupSet = false
			
			def emojiListFile = graphicsJar.getInputStream(graphicsJar.getEntry('txt/emojilist.txt'))
			emojiListFile.eachLine('UTF-8'){ String line ->
	 			if(line.startsWith('# group:')) {
	 				if(line.endsWith(': Component')){
	 					group = null
	 				}
	 				else {
	 					group = root.appendNode('Entry')
	 					group.attributes().put('description', line.substring(line.indexOf(':') + 2))
	 					group.attributes().put('type', 'group')
	 				}
	 			}
	 			else if(group != null) {  
		 			if(line.startsWith('# subgroup:')) {
		 				subgroup = group.appendNode('Entry')
		 				subgroup.attributes().put('description', line.substring(line.indexOf(':') + 2))
		 				subgroup.attributes().put('type', 'subgroup')
		 			}
		 			else if(line.length() > EMOJI_POSITION  && line.charAt(HEX_CODEPOINT_END_POSITION) == ';' && line.charAt(STATUS_END_POSITION) == '#') {
		 				String hexCodes = line.substring(0, HEX_CODEPOINT_END_POSITION).trim()
		 				String twemojiFileName = hexCodes.toLowerCase().replace(' ', '-').replaceFirst("^00", "") + '.svg';
				    	if (graphicsJar.getEntry("images/emoji/$twemojiFileName") != null) {
				    		int emojiEnd = line.indexOf(' ', EMOJI_POSITION)
					 		String emoji = line.substring(EMOJI_POSITION, emojiEnd)
					 		int commentStart = line.indexOf(' ', emojiEnd + 1) + 1
					 		String description = line.substring(commentStart)
					 		if(! description.startsWith('flag: ') && ! description.startsWith('keycap: ') && description.contains(': ')) {
					 			if (variantSubgroup == null) {
					 				variantSubgroup = subgroup.appendNode('Entry')
					 				variantSubgroup.attributes().put('type', 'variants')
					 				
					 				String actionDescription = action.attributes().get('description');
					 				if(description.startsWith(actionDescription + ':') 
					 					&& subgroup.remove(action)) {
					 						variantSubgroup.append(action)
					 						variantSubgroup.attributes().put('description', actionDescription)
							 				variantSubgroup.attributes().put('emoji', action.attributes().get('emoji'))
							 				variantSubgroup.attributes().put('file', action.attributes().get('file'))
					 				}
					 				else {
						 				variantSubgroup.attributes().put('description', description.replaceFirst(': .*', ''))
						 				variantSubgroup.attributes().put('emoji', emoji)
						 				variantSubgroup.attributes().put('file', twemojiFileName)
					 				}
					 			}
				 				action = variantSubgroup.appendNode('Entry')
					 		}
					 		else {
					 			variantSubgroup = null
			 					action = subgroup.appendNode('Entry')
			 				}
			 				group.attributes().putIfAbsent('emoji', emoji)
			 				group.attributes().putIfAbsent('file', twemojiFileName)
			 				subgroup.attributes().putIfAbsent('emoji', emoji)
			 				subgroup.attributes().putIfAbsent('file', twemojiFileName)
			 				action.attributes().put('emoji', emoji)
			 				action.attributes().put('type', 'emoji')
			 				action.attributes().put('entity', hexCodes)
			 				action.attributes().put('file', twemojiFileName)
		 					action.attributes().put('description', description.startsWith('flag: ') ? description.substring(6) : description)
			 			}	
		 			}
	 			}	
			}
			def emojiEntriesFile = new File(emojiDirectory, 'xml/images/emoji/xml/emojientries.xml')
			emojiEntriesFile.parentFile.mkdirs()
			emojiEntriesFile.withWriter('UTF-8') { writer ->
				writer.write(groovy.xml.XmlUtil.serialize(root))
			}
		}
		
		return this
	}
}

task createEmojiList {
	outputs.dir("${project.buildDir}/emoji/xml")
	
	doLast {
		UiEntryCreator.createUiEntryFile(file("$buildDir/emoji"), configurations.emoji.singleFile)
	}
}
