package com.ztoday21.refreshPie;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

public class service_main extends Service implements OnTouchListener {
	
	// °ª °øÀ¯
	public static int		_interval = 0;
	public static int		_timeInterval = 0;
	public static boolean	_isRunning = false;
	
	// ³»ºÎ »ç
	public TextView		_tv;		
	public Intent		_refreshIntent;

	@Override
	public void onCreate() 
	{
        super.onCreate();
    }
 
	@Override
    public void onDestroy() 
    {
        super.onDestroy();
        Toast.makeText(this, "¼­ºñ½º ÁßÁöµÊ", Toast.LENGTH_SHORT).show();
        _isRunning = false;
        
        // window manager ¿¡¼­ view Á¦°Å
        // ¼­ºñ½º°¡ ¸ØÃçµµ ÀÌºÎºÐÀÌ Á¦°Å°¡ ¾ÈµÇ¾úÀ½
        WindowManager winmgr = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
        winmgr.removeView(_tv);
        
        // ÈÄ¿¡ Á» ´õ Á¤È®ÇÑ ¼­ºñ½º ±â´É ¾Ë¾Æ¾ß ÇÔ
        
    }
    
	@Override
	public int onStartCommand(Intent intent, int flags, int startId )
	{
		if( 0 != (Service.START_FLAG_RETRY & flags) )
		{
			// ¿øÇÏ´Â ÀÛ¾÷À» ÇÏÀÚ
			// ¸®ÇÁ·¹½Ã¾îÇÃ Ã£±â
			
			// Å©·¹¸¶ ÅÍÄ¡
			_refreshIntent = getPackageManager().getLaunchIntentForPackage("com.nextpapyrus.Refresh2");

			// Å©·¹¸¶ »þÀÎ
			if(null == _refreshIntent)
				_refreshIntent = getIntentByLabel("ntx.epd", "ntx.epd.FullRefreshActivity");	
			
			if(true == _isRunning) {
				Toast.makeText(this, "ÀÌ¹Ì ¼­ºñ½º°¡ ½ÇÇàÁßÀÔ´Ï´Ù.", Toast.LENGTH_SHORT).show();
			}
			else if(null != _refreshIntent)
			{
				// text view ¸¦ window manager ¿¡ µî·Ï ÈÄ touch event ¿¬°á 
				_tv = new TextView(this);
				_tv.setOnTouchListener(this);
				
				WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				            WindowManager.LayoutParams.WRAP_CONTENT,
				            WindowManager.LayoutParams.WRAP_CONTENT,
				            WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
				            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
				                    | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
				            PixelFormat.TRANSLUCENT);
				
				WindowManager winmgr = (WindowManager)getSystemService(Context.WINDOW_SERVICE);

				winmgr.addView(_tv, lp);	
				
				Toast.makeText(this, "¼­ºñ½º ½ÃÀÛµÊ", Toast.LENGTH_SHORT).show();
				_isRunning = true;
			}
			else
			{
				// ¼­ºñ½º ½ÃÀÛ ½ÇÆÐ
				stopSelf(startId);		
				Toast.makeText(this, "¼­ºñ½º ½ÃÀÛ ½ÇÆÐ", Toast.LENGTH_SHORT).show();
				_isRunning = false;
			}
		}
		
		return Service.START_STICKY;
	}
	
	public Intent getIntentByLabel(String pkg, String cls) {
		Intent i = new Intent();
		i.setComponent(new ComponentName(pkg, cls));
		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_CLEAR_TOP);
		return i;
	}
	
	//---------------------------------
	public int _touchCnt;

	@Override
	public boolean onTouch(View v, MotionEvent event)
	{
		// ÀÌº¥Æ®¿¡ ´ëÇÑ ±â´É È®ÀÎ ÇÊ¿ä 
		// ¿Ö ÀÏÄÉ ¾Ë¾Æ¾ß ÇÒ°Ô ¸¹À» ±î³ª... -_-;;;
		
		//InputMethodManager ime = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		//if( false == ime.isAcceptingText() )
		{
			_touchCnt++;
			
			if( service_main._interval <= _touchCnt )
			{
				// ÅÍÄ¡ ÃÊ±âÈ­
				_touchCnt = 0;
				
				// ¸®ÇÁ·¹½Ã ¾îÇÃ ½ÇÇà
				if(null != _refreshIntent)
				{
					try
					{
						Thread.sleep(service_main._timeInterval);
					}
					catch( InterruptedException e )
					{
						Toast.makeText(service_main.this, e.toString(), Toast.LENGTH_LONG).show();
					}
					
					startActivity(_refreshIntent);
				}
			}
		}
		
		return false;
	}

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
}
