package com.viaccessorca.voplayerdemo.mediamgt;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MediaTypeMapper implements MediasMapperInterface {

	private MediaFinderInterface mediaFinder;

	public static final String STREAMS_MAP_KEY = "Streams";
	//public static final String LOCAL_FILES_MAP_KEY = "Local files";
	public static final String SUBTITLE_FILES_MAP_KEY = "Subtitles";

	private Map<String, List<MediaItem>> mappedMedias;

	public MediaTypeMapper(MediaFinderInterface mediaFinder) {
		super();
		this.mediaFinder = mediaFinder;
		mappedMedias = new HashMap<String, List<MediaItem>>();

		mappedMedias.put(STREAMS_MAP_KEY, new ArrayList<MediaItem>(0));
		//mappedMedias.put(LOCAL_FILES_MAP_KEY, new ArrayList<MediaItem>(0));
		mappedMedias.put(SUBTITLE_FILES_MAP_KEY, new ArrayList<MediaItem>(0));
		refresh();
	}

	public void setMediaFinder(MediaFinderInterface mediaFinder) {
		this.mediaFinder = mediaFinder;
		refresh();
	}

	@Override
	public void refresh() {

		mediaFinder.refresh();

		mappedMedias.get(STREAMS_MAP_KEY).clear();
		//mappedMedias.get(LOCAL_FILES_MAP_KEY).clear();
		mappedMedias.get(SUBTITLE_FILES_MAP_KEY).clear();
		sortMediasByType();
		sortMaps();
	}

	private void sortMediasByType() {

		Collection<MediaItem> medias = mediaFinder.getMedias();
		for(MediaItem item: medias) {

			switch(item.getMediaType()) {
			case HTTP_STREAMING_MEDIA:
			case HTTP_STREAMING_MEDIA_EBD:
            case MEDIA_PLAYLIST:
				mappedMedias.get(STREAMS_MAP_KEY).add(item);
				break;/*
			case LOCAL_MEDIA:
				mappedMedias.get(LOCAL_FILES_MAP_KEY).add(item);
				break;
				*/
			case SUBTITLE_FILE:
				mappedMedias.get(SUBTITLE_FILES_MAP_KEY).add(item);
				break;
			default:
				break;
			}
		}
	}

	private void sortMaps() {
		Collections.sort(mappedMedias.get(STREAMS_MAP_KEY));
		//Collections.sort(mappedMedias.get(LOCAL_FILES_MAP_KEY));
		Collections.sort(mappedMedias.get(SUBTITLE_FILES_MAP_KEY));
	}

	@Override
	public Map<String, List<MediaItem>> getMappedMedias() {
		return mappedMedias;
	}
}
