package com.howard.rockear.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.howard.rockear.Utils.QuerTools;
import com.howard.rockear.adapters.TrackListContent;
import com.howard.rockear.config.ConfigManager;
import com.howard.rockear.database.DataBaseHelper;
import com.rockear.lrc.LrcUtils;

/**
 * @author howard app service
 * 
 */
public class RockEarService extends Service implements OnCompletionListener {

	// constants
	public static boolean ISPLAYING = false;

	// now playing track info
	public static ArrayList<TrackListContent> NOW_PLAYING_LIST;
	public static int NOW_PLAYING_INDEX = 0;
	public static String NOW_PLAYING_TITLE = "";
	public static String NOW_PLAYING_ARTIST = "";
	public static String NOW_PLAYING_ALBUM = "";
	public static String NOW_PLAYING_PATH = "";
	public static String NOW_PLAYING_LETTER = "";
	public static long NOW_PLAYING_ALBUM_ID = 0;
	public static long NOW_PLAYING_ID = 0;
	public static String NOW_DURATION = "";

	public static int NOW_PLAYING_TIME = -1;
	public static int CURRENT_PLAY_MOD = -1;

	// preference manager
	private ConfigManager mConfigManager;

	// database
	private DataBaseHelper mDataBaseHelper;
	private SQLiteDatabase mDatabase;
	private int DB_VERSION = 1;

	// tools
	QuerTools querTools;

	// player
	private RockPlayer mediaPlayer = new RockPlayer();

	// activity the callBack the service methods
	private IEarActivity mActivityCallBack;

	// binder
	private IEarService.Stub mBinderStub = new ServiceStub(this);

	@Override
	public IBinder onBind(Intent intent) {
		if (mBinderStub != null) {
			return mBinderStub;
		}
		return null;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// manager
		mConfigManager = new ConfigManager(this);
		querTools = new QuerTools(this);
		return super.onStartCommand(intent, flags, startId);
	}

	/**
	 * @throws RemoteException
	 *             1repeat all 3random 4repeat one
	 */
	public void setPlayMod(int whitch) throws RemoteException {
		mConfigManager.setPlayModConfig(whitch);
	}

	public void resumeTrack() throws RemoteException {
		if (NOW_PLAYING_INDEX >= 0) {
			mediaPlayer.start();
		}
		ISPLAYING = true;
		mActivityCallBack.setPlayBtnBg();
	}

	public void registerCallBack(IEarActivity activity) throws RemoteException {
		mActivityCallBack = activity;

	}

	public void playPrevious() throws RemoteException {
		CURRENT_PLAY_MOD = getPlayMod();
		switch (CURRENT_PLAY_MOD) {
		case 0:
			if (NOW_PLAYING_INDEX == 0) {
				NOW_PLAYING_INDEX = 0;
			} else {
				NOW_PLAYING_INDEX = NOW_PLAYING_INDEX - 1;
			}
			break;
		case 1:
			if (NOW_PLAYING_INDEX == 0) {
				NOW_PLAYING_INDEX = NOW_PLAYING_LIST.size() - 1;
			} else {
				NOW_PLAYING_INDEX = NOW_PLAYING_INDEX - 1;
			}
			break;
		case 2:
			NOW_PLAYING_INDEX = new Random()
					.nextInt(NOW_PLAYING_LIST.size() - 1);
			break;
		case 3:
			break;
		default:
			NOW_PLAYING_INDEX = 0;
			break;
		}

		playTrack();
		ISPLAYING = true;
		mActivityCallBack.setPlayBtnBg();
	}

	/**
	 * @throws RemoteException
	 */
	public void playNext() throws RemoteException {

		CURRENT_PLAY_MOD = getPlayMod();
		switch (CURRENT_PLAY_MOD) {
		case 0:
			if (NOW_PLAYING_INDEX == NOW_PLAYING_LIST.size() - 1) {
				mediaPlayer.stop();
			} else {
				NOW_PLAYING_INDEX = NOW_PLAYING_INDEX + 1;
			}
			break;
		case 1:
			if (NOW_PLAYING_INDEX == NOW_PLAYING_LIST.size() - 1) {
				NOW_PLAYING_INDEX = 0;
			} else {
				NOW_PLAYING_INDEX = NOW_PLAYING_INDEX + 1;
			}
			break;
		case 2:
			NOW_PLAYING_INDEX = new Random()
					.nextInt(NOW_PLAYING_LIST.size() - 1);
			break;
		case 3:
			break;
		}

		playTrack();
		ISPLAYING = true;
		// update the play button
		mActivityCallBack.setPlayBtnBg();
	}

	public void pauseTrack() throws RemoteException {
		mediaPlayer.pause();
		ISPLAYING = false;
		mActivityCallBack.setPlayBtnBg();
	}

	/**
	 * play music by using the now playing constants....
	 */
	public void playTrack() {

		NOW_PLAYING_PATH = NOW_PLAYING_LIST.get(NOW_PLAYING_INDEX)
				.getUrlString();

		if (NOW_PLAYING_INDEX >= 0) {
			try {
				mediaPlayer.reset();
				mediaPlayer.setDataSource(NOW_PLAYING_PATH);
				mediaPlayer.prepare();
				mediaPlayer.start();

				try {
					// set max
					mActivityCallBack.setSeekbar(mediaPlayer.getDuration());
				} catch (RemoteException e) {
					e.printStackTrace();
				}

			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			ISPLAYING = true;
			mediaPlayer.setOnCompletionListener(this);
			try {
				mActivityCallBack.setPlayBtnBg();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}

	}

	private void updateCont() {
		// update info
		NOW_PLAYING_TITLE = NOW_PLAYING_LIST.get(NOW_PLAYING_INDEX)
				.getTitleString();
		NOW_PLAYING_ARTIST = NOW_PLAYING_LIST.get(NOW_PLAYING_INDEX)
				.getArtistString();
		NOW_PLAYING_ALBUM = NOW_PLAYING_LIST.get(NOW_PLAYING_INDEX)
				.getAlbumString();
		NOW_PLAYING_ALBUM_ID = NOW_PLAYING_LIST.get(NOW_PLAYING_INDEX)
				.getAlbumId();
		NOW_PLAYING_ID = NOW_PLAYING_LIST.get(NOW_PLAYING_INDEX).getId();
		NOW_DURATION = NOW_PLAYING_LIST.get(NOW_PLAYING_INDEX)
				.getDurationString();
		NOW_PLAYING_LETTER = NOW_PLAYING_LIST.get(NOW_PLAYING_INDEX)
				.getLetterString();
	}

	private void seekTo(int where) {
		mediaPlayer.seekTo(where);
	}

	private int getCurrentSeekTime() {
		return mediaPlayer.getCurrentPosition();
	}

	public void notifyChnaged() throws RemoteException {
		// TODO Auto-generated method stub

	}

	public int getPlayMod() throws RemoteException {
		return mConfigManager.getPlayMod();
	}

	/**
	 * @throws RemoteException
	 *             add to local database
	 */
	public void addToFavourite() throws RemoteException {

		long id = NOW_PLAYING_ID;
		boolean has = querTools.checkIfHasAsFavourite(id, "Favourite.db",
				"mTable", 1);
		if (has) {
			querTools.removeTrackFrmDatabase(id, "Favourite.db", "mTable", 1);
			// no
			mActivityCallBack.setPraisedBtn(1);
		} else {
			addToDataBase("Favourite.db");
			// ed
			mActivityCallBack.setPraisedBtn(2);
		}

		// update the list contents
		mActivityCallBack.updateList();
	}

	public void testForService() throws RemoteException {
		mActivityCallBack.test();
	}

	public void saveRecentData() {
		addToDataBase("Recent.db");
	}

	private void addToDataBase(String dbName) {
		if (NOW_PLAYING_TITLE != "") {
			mDataBaseHelper = new DataBaseHelper(this, dbName, null, DB_VERSION);
			mDatabase = mDataBaseHelper.getWritableDatabase();

			ContentValues values = new ContentValues();
			values.put("TITLE", NOW_PLAYING_TITLE);
			values.put("ARTIST", NOW_PLAYING_ARTIST);
			values.put("ALBUM", NOW_PLAYING_ALBUM);
			values.put("DURATION", NOW_DURATION);
			values.put("PATH", NOW_PLAYING_PATH);
			values.put("SONG_ID", NOW_PLAYING_ID);
			values.put("ALBUM_ID", NOW_PLAYING_ALBUM_ID);
			values.put("LETTER", NOW_PLAYING_LETTER);
			values.put("ADDED_TIME", System.currentTimeMillis());
			mDatabase.insert("mTable", null, values);
		}
	}

	// stub of the stub -->>
	// activity invoke these methods
	class ServiceStub extends IEarService.Stub {

		private RockEarService mService;

		/**
		 * @param mService
		 */
		public ServiceStub(RockEarService mService) {
			super();
			this.mService = mService;
		}

		@Override
		public void registerCallBack(IEarActivity activity) throws RemoteException {
			mService.registerCallBack(activity);

		}

		@Override
		public void testForService() throws RemoteException {
			mService.testForService();

		}

		@Override
		public void playNext() throws RemoteException {
			mService.playNext();

		}

		@Override
		public void playPrevious() throws RemoteException {
			mService.playPrevious();

		}

		@Override
		public void pauseTrack() throws RemoteException {
			mService.pauseTrack();

		}

		@Override
		public void resumeTrack() throws RemoteException {
			mService.resumeTrack();

		}

		@Override
		public int getPlayMod() throws RemoteException {
			mService.getPlayMod();
			return 0;
		}

		@Override
		public void notifyChnaged() throws RemoteException {
			mService.notifyChnaged();

		}

		@Override
		public void addToFavourite() throws RemoteException {
			mService.addToFavourite();

		}

		@Override
		public void setPlayMod(int whitch) throws RemoteException {
			mService.setPlayMod(whitch);

		}

		@Override
		public void playTrack() throws RemoteException {
			mService.playTrack();

		}

		@Override
		public void seekTo(int where) throws RemoteException {
			mService.seekTo(where);

		}

		@Override
		public int getCurrentSeekTime() throws RemoteException {

			return mService.getCurrentSeekTime();
		}

		@Override
		public void saveRecentData() throws RemoteException {
			mService.saveRecentData();
		}
	}

	/*
	 * on track complete
	 */
	@Override
	public void onCompletion(MediaPlayer arg0) {
		try {
			playNext();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	class RockPlayer extends MediaPlayer {

		@Override
		public void pause() throws IllegalStateException {

			updateCont();
			try {
				mActivityCallBack.toogleSmartBar(0);
				mActivityCallBack.updateBottomArt();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			super.pause();
		}

		@Override
		public void start() throws IllegalStateException {

			updateCont();
			try {
				mActivityCallBack.toogleSmartBar(0);
				mActivityCallBack.updateBottomArt();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			super.start();
			// save something
			saveRecentData();
			try {
				mActivityCallBack.updatePraisedBtn();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			new LrcUtils().new GetJsonLrc(NOW_PLAYING_TITLE, NOW_PLAYING_ARTIST)
					.execute("");
			Log.e("howard", "task lrc started>>>>>>>>");
		}

	}
}
