#!/usr/bin/env python

import help_parser as hp
import os
import sys
import shutil
import lxml.etree as ET


def parse_args():
	parser = hp.HelpParser(description='Helper program to copy images by classes according to XML file')
	parser.add_argument('xml', help='Input XML file')
	parser.add_argument('-dir', dest='dir', help='Folder to save files [dir of XML file]', default=None)

	args = parser.parse_args()
	return args


def cpclass(file, cl, folder):
	ff = os.path.join(folder, cl)
	if not os.path.isdir(ff):
		os.mkdir(ff)
	shutil.copy(file, ff)


def convert_data(data, folder):
	file = data.get('newpath')
	for object in data.iter('object'):
		cpclass(file, object.get('class'), folder)
	if len(data) is 0:n
		cpclass(file, 'nothing', folder)		


if __name__ == '__main__':
	args = parse_args()
	xml = ET.parse(args.xml)
	root = xml.getroot()
	if root.get('type') != 'folder':
		raise ValueError('You can process only XML file coming from \'folder\' type experiment!')
	
	if args.dir is None:
		args.dir = os.path.dirname(args.xml)
	
	for child in root.iter('file'):
		convert_data(child, args.dir)
