package com.howard.rockear.activity;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

import com.howard.rockear.R;
import com.howard.rockear.Utils.ImageProvider;
import com.howard.rockear.Utils.QuerTools;
import com.howard.rockear.fragment.FragmentAllTracks;
import com.howard.rockear.fragment.FragmentArtists;
import com.howard.rockear.fragment.FragmentFavourite;
import com.howard.rockear.fragment.FragmentMenuDrawer;
import com.howard.rockear.fragment.FragmentSmartBarHolder;
import com.howard.rockear.service.IEarActivity;
import com.howard.rockear.service.IEarService;
import com.howard.rockear.service.RockEarService;
import com.howard.rockear.views.CircleTextView;
import com.howard.rockear.views.SmartBar.SmartBarHandle;

public class ActivityRockEar extends ActionBarActivity implements
		FragmentMenuDrawer.NavigationDrawerCallbacks, SmartBarHandle {

	private FragmentMenuDrawer mNavigationDrawerFragment;
	private SectionsPagerAdapter mSectionsPagerAdapter;
	private ViewPager mViewPager;

	private CharSequence mTitle;
	private String TAG = "howard";
	private DrawerLayout mDrawerLayout = null;

	public static LinearLayout progressBar = null;
	public static CircleTextView mDiaTextView;

	private WindowManager mWindowManager = null;

	// pages
	private FragmentAllTracks fragment_main;
	private FragmentArtists fragment_artist;
	private FragmentFavourite fragment_favourite;

	// indicator

	private FragmentSmartBarHolder mSmartDampFragment = null;
	private boolean isShowing = false;

	// btn
	private ImageButton playButton;
	private ImageButton nextButton;
	private ImageButton previousButton;
	private ImageButton setFavourButton;
	private ImageButton playModButton;

	// seekbar
	private SeekBar seekBar;
	private Handler mSeekHandler = new Handler();

	// image view
	private ImageView bottomArtImageView;
	// tools
	private QuerTools qTools;

	// ensure that the activity is started already before we add window
	@SuppressLint("HandlerLeak")
	private Handler childViewHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				initListPositionView();
				break;
			}
		}

	};

	// service
	private IEarActivity.Stub mCallBack = new IEarActivity.Stub() {

		@Override
		public void test() throws RemoteException {
			Toast.makeText(getApplicationContext(),
					"frm service callback  this method", Toast.LENGTH_SHORT)
					.show();
		}

		@Override
		public void setSeekbar(int howmuch) throws RemoteException {
			if (seekBar != null) {
				seekBar.setMax(howmuch);
			}

		}

		@Override
		public void setPlayBtnBg() throws RemoteException {
			setBottomPlayBtnBg();
		}

		@Override
		public void setDefaultTrackList() throws RemoteException {
			RockEarService.NOW_PLAYING_INDEX = 0;
		}

		@Override
		public void toogleSmartBar(int mod) throws RemoteException {
			toogleTheSmartBar(mod);

		}

		@Override
		public void updateBottomArt() throws RemoteException {
			updateBottomViewArtImage();
		}

		// update the favbtn bg
		@Override
		public void updatePraisedBtn() throws RemoteException {
			updatePraisedBtnBg();
		}

		@Override
		public void updateList() throws RemoteException {
			if (fragment_favourite != null) {
				fragment_favourite.updateListData();
			}
		}

		@Override
		public void setPraisedBtn(int kind) throws RemoteException {
			// 1 no 2 ed
			setPraisedBtnBg(kind);
		}
	};

	/**
	 * connection
	 */
	public IEarService mServiceCallBack;

	private ServiceConnection mServiceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mServiceCallBack = null;
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mServiceCallBack = IEarService.Stub.asInterface(service);
			try {
				mServiceCallBack.registerCallBack(mCallBack);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// set volume as media
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		// this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.activity_main);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the activity.
		mSectionsPagerAdapter = new SectionsPagerAdapter(
				getSupportFragmentManager());

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);
		
		// set the title
		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {
				switch (arg0) {
				case 0:
					getSupportActionBar().setTitle(
							getResources().getString(R.string.title_local));
					break;
				case 1:
					getSupportActionBar().setTitle(
							getResources().getString(R.string.title_favourite));
					break;
				case 2:
					getSupportActionBar().setTitle(
							getResources().getString(R.string.title_artist));
					break;

				default:
					break;
				}

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});

		// init drawer
		mNavigationDrawerFragment = (FragmentMenuDrawer) getSupportFragmentManager()
				.findFragmentById(R.id.navigation_drawer);
		mTitle = "����";

		getSupportActionBar().setBackgroundDrawable(
				getResources().getDrawable(R.color.white));

		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
				(DrawerLayout) findViewById(R.id.drawer_layout));

		// init drawerLayout
		mDrawerLayout = mNavigationDrawerFragment.mDrawerLayout;

		// init WindowManager��tell handler that the activity is ready
		mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		Log.i(TAG, "" + mWindowManager);

		childViewHandler.sendEmptyMessageDelayed(0, 1000);

		// start and bind service
		final Intent _Intent = new Intent(ActivityRockEar.this,
				RockEarService.class);
		bindService(_Intent, mServiceConnection, BIND_AUTO_CREATE);
		startService(_Intent);

		// button
		initBtn();
		// seekBar update
		initSeekBar();
		mSeekHandler.post(new Runnable() {

			@Override
			public void run() {
				try {
					if (seekBar != null && RockEarService.ISPLAYING) {
						seekBar.setProgress(mServiceCallBack
								.getCurrentSeekTime());
					}
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				mSeekHandler.postDelayed(this, 1000);
			}
		});

		// artIcon imageView
		initBottomArt();
		// db tools initial
		qTools = new QuerTools(this);
	}

	@Override
	protected void onResume() {
		try {
			setBottomPlayBtnBg();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// unBind here
		unbindService(mServiceConnection);
		// remove the views we added
		mWindowManager.removeView(mDiaTextView);
		super.onDestroy();
	}

	@Override
	public void onNavigationDrawerItemSelected(int position) {
		switch (position) {
		case 0:
			break;
		case 1:
			try {
				mServiceCallBack.testForService();
			} catch (RemoteException e) {
				e.printStackTrace();
			}
			break;
		case 2:
			break;

		default:
			break;
		}

	}

	public void restoreActionBar() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle(mTitle);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (!mNavigationDrawerFragment.isDrawerOpen()) {
			// Only show items in the action bar relevant to this screen
			// if the drawer is not showing. Otherwise, let the drawer
			// decide what to show in the action bar.
			getMenuInflater().inflate(R.menu.main, menu);
			restoreActionBar();
			return true;
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_search) {
			toogleTheSmartBar(0);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			toogleDrawer();
			Log.i(TAG, "menu pressed");
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	// open or close the menu
	private void toogleDrawer() {

		if (mDrawerLayout.isDrawerVisible(GravityCompat.START)) {
			mDrawerLayout.closeDrawer(GravityCompat.START);
		} else {
			mDrawerLayout.openDrawer(GravityCompat.START);
		}

	}

	/**
	 * add view
	 */
	public void initListPositionView() {


		mDiaTextView = (CircleTextView) LayoutInflater.from(this).inflate(
				R.layout.list_position, null);
		mDiaTextView.setVisibility(View.INVISIBLE);

		WindowManager.LayoutParams params = new WindowManager.LayoutParams(
				160,
				160,
				android.view.WindowManager.LayoutParams.TYPE_APPLICATION_PANEL,
				android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
						| android.view.WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
				PixelFormat.TRANSLUCENT);

		if (mWindowManager != null) {
			mWindowManager.addView(mDiaTextView, params);
			Log.d(TAG, "*****************************************"
					+ mWindowManager);
			if (fragment_main != null) {
				fragment_main.setDialogTextView(mDiaTextView);
			}
			if (fragment_favourite != null) {
				fragment_favourite.setDialogTextView(mDiaTextView);
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.howard.rockear.views.DampView.ImgClickHandler#handleImgClick()
	 */

	/**
	 * @param how
	 *            hile or show
	 */
	public void toogleTheSmartBar(int how) {

		switch (how) {
		case 0:
			if (mSmartDampFragment == null) {
				mSmartDampFragment = new FragmentSmartBarHolder();
				getSupportFragmentManager()
						.beginTransaction()
						.setCustomAnimations(R.anim.view_push_down_in,
								R.anim.view_push_down_in)
						.replace(R.id.container, mSmartDampFragment).commit();
				isShowing = true;
			}

			else if (mSmartDampFragment != null && !isShowing) {
				mSmartDampFragment.updateImageView();
				mSmartDampFragment.updateTextView();
				getSupportFragmentManager()
						.beginTransaction()
						.setCustomAnimations(R.anim.view_push_down_in,
								R.anim.view_push_down_in)
						.show(mSmartDampFragment).commit();
				isShowing = true;
			}
			mSmartDampFragment.updateImageView();
			mSmartDampFragment.updateTextView();
			break;
		case 1:
			if (isShowing) {
				getSupportFragmentManager()
						.beginTransaction()
						.setCustomAnimations(R.anim.view_push_down_out,
								R.anim.view_push_down_out)
						.hide(mSmartDampFragment).commit();
			}
			isShowing = false;
			break;
		}

	}

	/**
	 * initial the btns
	 */
	private void initBtn() {
		playButton = (ImageButton) findViewById(R.id.btn_play_local);
		nextButton = (ImageButton) findViewById(R.id.btn_next_local);
		previousButton = (ImageButton) findViewById(R.id.btn_pre_local);
		setFavourButton = (ImageButton) findViewById(R.id.btn_praised);
		playModButton = (ImageButton) findViewById(R.id.btn_playmod_main);

		playButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (RockEarService.ISPLAYING) {
					try {
						mServiceCallBack.pauseTrack();
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				} else {
					try {
						mServiceCallBack.resumeTrack();
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
			}
		});

		previousButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					mServiceCallBack.playPrevious();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});

		nextButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					mServiceCallBack.playNext();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});

		setFavourButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				try {
					mServiceCallBack.addToFavourite();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}
		});

		playModButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int i = -1;
				try {
					i = mServiceCallBack.getPlayMod();
				} catch (RemoteException e) {
					e.printStackTrace();
				}
				switch (i) {
				case -1:
					break;
				case 1:
					try {
						mServiceCallBack.setPlayMod(2);
						playModButton
								.setBackgroundResource(R.drawable.play_list_mode_repeat_one);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
					break;
				case 2:
					try {
						mServiceCallBack.setPlayMod(3);
						playModButton
								.setBackgroundResource(R.drawable.play_list_mode_shuffle);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
					break;
				case 3:
					try {
						mServiceCallBack.setPlayMod(1);
						playModButton
								.setBackgroundResource(R.drawable.play_list_mode_sequent);
					} catch (RemoteException e) {
						e.printStackTrace();
					}
					break;
				}
			}
		});
	}

	public void setBottomPlayBtnBg() throws RemoteException {
		if (RockEarService.ISPLAYING) {
			playButton.setImageResource(R.drawable.btn_pause);
		} else {
			playButton.setImageResource(R.drawable.btn_play);
		}

	}

	public void setPraisedBtnBg(int kind) throws RemoteException {
		switch (kind) {
		case 1:
			setFavourButton.setImageResource(R.drawable.like_no);
			break;
		case 2:
			setFavourButton.setImageResource(R.drawable.like_ed);
			break;
		}

	}

	private void updatePraisedBtnBg() {
		if (qTools != null) {
			boolean has = qTools.checkIfHasAsFavourite(
					RockEarService.NOW_PLAYING_ID, "Favourite.db", "mTable", 1);
			if (has) {
				setFavourButton.setImageResource(R.drawable.like_ed);
			} else {
				setFavourButton.setImageResource(R.drawable.like_no);
			}
		}
	}

	private void initSeekBar() {

		seekBar = (SeekBar) findViewById(R.id.seekbar_playing);
		seekBar.setMax(1000);
		seekBar.setSoundEffectsEnabled(true);
		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar arg0) {
				try {
					mServiceCallBack.seekTo(RockEarService.NOW_PLAYING_TIME);
				} catch (RemoteException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar arg0) {

			}

			@Override
			public void onProgressChanged(SeekBar arg0, int position,
					boolean arg2) {
				RockEarService.NOW_PLAYING_TIME = position;
			}
		});

	}

	private void initBottomArt() {
		bottomArtImageView = (ImageView) findViewById(R.id.iv_art_bottom);
		bottomArtImageView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				toogleTheSmartBar(0);
			}
		});
	}

	private void updateBottomViewArtImage() {
		bottomArtImageView.setImageBitmap(ImageProvider.getArtWork(
				this,
				RockEarService.NOW_PLAYING_LIST.get(
						RockEarService.NOW_PLAYING_INDEX).getId(),
				RockEarService.NOW_PLAYING_LIST.get(
						RockEarService.NOW_PLAYING_INDEX).getAlbumId(), true));
	}

	@Override
	public void onBackPressed() {
		if (isShowing) {
			toogleTheSmartBar(1);
		} else {
			finish();
		}
	}

	/**
	 * @author howard pager adapter
	 * 
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		public SectionsPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			case 0:
				fragment_main = new FragmentAllTracks();
				return fragment_main;
			case 1:
				fragment_favourite = new FragmentFavourite();
				return fragment_favourite;
			case 2:
				fragment_artist = new FragmentArtists();
				return fragment_artist;
			default:
				break;
			}
			Log.i(TAG, position + "");
			return null;
		}

		@Override
		public int getCount() {
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			switch (position) {
			case 0:
				return getResources().getString(R.string.title_local);
			case 1:
				return getResources().getString(R.string.title_favourite);
			case 2:
				return getResources().getString(R.string.title_artist);
			}
			return null;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
		}

	}

	@Override
	public void handleAction() {
		toogleTheSmartBar(1);
	}

}
