/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
package com.xuxin.mychat.mina;

import java.net.SocketAddress;
import java.nio.charset.Charset;

import org.apache.mina.core.filterchain.IoFilter;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.logging.MdcInjectionFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import android.util.Log;

import com.google.gson.Gson;
import com.xuxin.mychat.model.MyMessage;

/**
 * A simple chat client for a given user.
 * 
 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
 */
public class ChatClientSupport {
	private final String name;
	private NioSocketConnector connector;
	private IoSession session;
	private final IoHandler handler;

	public ChatClientSupport(String name, IoHandler handler) {
		if (name == null) {
			throw new IllegalArgumentException("Name can not be null");
		}
		this.name = name;
		this.handler = handler;
	}

	public NioSocketConnector getConnector() {
		if (null != connector) {
			return connector;
		} else {
			connector = new NioSocketConnector();

			IoFilter LOGGING_FILTER = new LoggingFilter();

			IoFilter CODEC_FILTER = new ProtocolCodecFilter(
					new TextLineCodecFactory(Charset.forName("UTF-8")));

			connector.getFilterChain().addLast("loggingFilter", LOGGING_FILTER);
			connector.getFilterChain().addLast("mdcFilter",
					new MdcInjectionFilter());
			connector.getFilterChain().addLast("codecFilter", CODEC_FILTER);

			connector.setHandler(handler);

			return connector;
		}
	}

	// login out
	public void logout() {
		if (session != null && session.isConnected()) {
			session.close(true);
		}
	}

	// login in
	public boolean login(SocketAddress address) {
		try {
			MyMessage msg = new MyMessage();

			msg.setUsername(this.name);
			msg.setModel("login");
			msg.setMessage("login");

			Gson gson = new Gson();
			String json = gson.toJson(msg);

			if (session != null && session.isConnected()) {
				Log.i("[login]s", session.toString());
				Log.i("[login]s", json);
				session.write(json);
				return true;
			} else {
				connector = getConnector();
				ConnectFuture future1 = connector.connect(address);
				future1.awaitUninterruptibly();
				if (!future1.isConnected()) {
					return false;
				}
				session = future1.getSession();

				Log.i("[login]xx", session.toString());
				Log.i("[login]w", json);
				session.write(json);
				return true;
			}

		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

	}

	// send message
	public void broadcast(SocketAddress address, String message) {
		MyMessage msg = new MyMessage();

		msg.setUsername(this.name);
		msg.setModel("chat");
		msg.setMessage(message);

		Gson gson = new Gson();
		String json = gson.toJson(msg);

		if (session != null && session.isConnected()) {
			Log.i("xx", session.toString());
			session.write(json);
		} else {
			Log.i("xx", "session is null");

			try {
				connector = getConnector();
				ConnectFuture future1 = connector.connect(address);
				future1.awaitUninterruptibly();
				session = future1.getSession();
				Log.i("[chat]xx", session.toString());
				Log.i("[chat]w", json);
				session.write(json);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}
}
