package hiro.yoshioka.sql.resource.twitter;

import hiro.yoshioka.sql.resource.DBResource;
import hiro.yoshioka.util.FileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.URL;

public class TwitterUser extends DBResource implements Serializable {
	private static final long serialVersionUID = 4599361118797103088L;

	public TwitterUser(TwitterDBSchema parent) {
		super(parent);
	}

	public void setParent(TwitterDBSchema parent) {
		this._parent = parent;
	}

	private File getProfileImageFile() {
		String url = getPropertyValue(TwitterColumnType.profileImageUrlHttps
				.name());
		String postFix = "";
		if (url.lastIndexOf("/") > 0) {
			postFix = url.substring(url.lastIndexOf("/"));
		}
		File f = new File(FileUtil.CACHE_DIR, getName() + "__" + postFix);
		return f;
	}

	public File getProfileImage() {
		File f = getProfileImageFile();
		if (f == null || !f.exists()) {
			writeProfileImage();
		}
		return null;
	}

	private void writeProfileImage() {

		String urlString = getPropertyValue(TwitterColumnType.profileImageUrlHttps
				.name());
		System.out.println("write file path=" + urlString);
		InputStream in = null;
		OutputStream out = null;
		try {
			URL url = new URL(urlString);

			in = url.openStream();
			File outFile = getProfileImageFile();
			File dir = outFile.getParentFile();
			if (!dir.exists()) {
				dir.mkdirs();
			}

			System.out.println("dir=" + outFile.getAbsolutePath());
			out = new FileOutputStream(outFile);
			byte[] buf = new byte[1024];
			int len = 0;

			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}

			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean contain(String pattern) {
		return false;
	}

}