package org.jerrymouse.cc.site.bean;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import org.apache.commons.io.IOUtils;
import org.jerrymouse.cc.utils.ResourceBuilder;

public class Device {
	@SuppressWarnings("unchecked")
	public static List<Device> getDevices() {
		List<Device> devices = new ArrayList<Device>();
		InputStream inputStream = ResourceBuilder.getResourcesBuilder().load(
				"META-INF/deviceFormat");
		try {
			List<String> lines = IOUtils.readLines(inputStream);
			for (String l : lines) {
				devices.add(new Device(l));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return devices;
	}

	private List<Format> formats;

	private String name;

	public Device() {
	}

	public Device(String line) {
		Scanner scanner = new Scanner(new StringReader(line));
		this.name = scanner.next();
		while (scanner.hasNext()) {
			String s = scanner.next();
			if (formats == null)
				formats = new ArrayList<Format>();
			formats.add(new Format(s));
		}
	}

	// 0 is null,1 is just kind,2 is brand,3 is no,4 is name
	private int fit(Device device) {
		if (name.equals(device.getName()))
			return 4;
		int i = fit(getKind(), device.getKind());
		switch (i) {
		case 0:
			return 0;
		case 1:
			return 0;
		case 2: {
			i = fit(getBrand(), device.getBrand());
			switch (i) {
			case 0:
				return 0;
			case 1:
				return 1;
			case 2: {
				i = fit(getNo(), device.getNo());
				switch (i) {
				case 0:
					return 0;
				case 1:
					return 2;
				case 2:
					return 3;
				}
			}
			}
		}
		}
		return 0;
	}

	// 0 is no,1 is just fit,2 is equal
	private int fit(String a, String b) {
		if (a.equalsIgnoreCase(b)) {
			return 2;
		}
		if (a.equals("*") || b.equals("*")) {
			return 1;
		}
		return 0;
	}

	private String getKind() {
		String[] s = name.split("-");
		if (s.length < 1)
			return name;
		return s[0];
	}

	private String getBrand() {
		String[] s = name.split("-");
		if (s.length < 2)
			return "*";
		return s[1];
	}

	private String getNo() {
		String[] s = name.split("-");
		if (s.length < 3)
			return "*";
		return s[2];
	}

	private void fitBest() {
		Device fitBest = null;
		int max = 0;
		for (Device d : getDevices()) {
			int i = fit(d);
			if (i > max) {
				max = i;
				fitBest = d;
			}
		}
		formats = fitBest.getFormats();
	}

	public List<Format> getFormats() {
		if (formats == null) {
			fitBest();
		}
		return formats;
	}

	public String getName() {
		return name;
	}

	public void setFormats(List<Format> formats) {
		this.formats = formats;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Format toFormat(Type type) {
		for (Format f : getFormats()) {
			if (f.getType().belongsTo(type)) {
				return f;
			}
		}
		return null;
	}

	@Override
	public String toString() {
		String string = name + ":";
		for (Format f : getFormats()) {
			string += f + ",";
		}
		return string;
	}

}
