/**
 * 
 */
package org.arkiwi.app.activity;

import java.util.ArrayList;

import org.arkiwi.app.R;
import org.arkiwi.app.adapter.AdapterList;
import org.arkiwi.app.database.DbFeed;
import org.arkiwi.app.feed.FeedQuery;
import org.arkiwi.app.interfaces.SDialogInterface;
import org.arkiwi.app.rss.RssDoc;
import org.arkiwi.app.rss.RssReader;
import org.arkiwi.app.service.FeedBurnPrecario;
import org.arkiwi.app.utility.IcoCtxMenu;
import org.arkiwi.app.utility.SDialog;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class Archive extends ListActivity implements SDialogInterface {
	public final static String LOG_TAG = "Archive";
	public static Resources res;
	
	public final static int 
		MENU_REFRESH_ID = 20,
		MENU_ORDER_ID = 21,
		SUBMENU_ORDER_ID = 121;
	private final static int 
		MENUCTX_ITEM_MODIFY = 1, 
		MENUCTX_ITEM_REFRESH = 2,
		MENUCTX_ITEM_MOREI = 3,
		MENUCTX_ITEM_DELETE = 4;
	private static IcoCtxMenu icoCtxMenu;
	private static int ctxMenuItemPos = -1;
	private static Dialog dialog;
	private static String qOrder, iOrder;
	private Intent feedBurnPI;
	
	private static DbFeed db;
	private static ArrayList<FeedQuery> fq;

    AdapterList listAdapter;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.archive_main);
		res = getResources();
		feedBurnPI = new Intent(this,FeedBurnPrecario.class);
	}
	
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		RssReader rss = RssReader.getInstance();
		RssDoc docs = RssDoc.getInstance(ATab.max_cache);
		FeedQuery q = fq.get(position);
		
		db.openR();
		db.fillItem(q, q.getQid(), iOrder);
		
		if(RssReader.getFromState()==RssReader.STATE_BACK_VIEWER)
			RssReader.setFromState(RssReader.STATE_INIT_VIEWER);
		
		rss.clearFeedQuery();
		rss.setFeedQuery(q);
		
		docs.treeClear();
		docs.treePushElement(q.getLink());
		
		ATab.tabHost.setCurrentTab(1);
	}
	
	private void fillContextMenus() {
		icoCtxMenu
			.addItem(res, R.string.diag_act_modify, R.drawable.modify, MENUCTX_ITEM_MODIFY);
		icoCtxMenu
			.addItem(res, R.string.diag_act_refresh, R.drawable.synchronize, MENUCTX_ITEM_REFRESH);
		icoCtxMenu
			.addItem(res, R.string.diag_act_delete, R.drawable.delete, MENUCTX_ITEM_DELETE);
		icoCtxMenu
			.addItem(res, R.string.diag_act_morei, R.drawable.morei, MENUCTX_ITEM_MOREI);
	}
	
	private void setCallbackContextMenu(IcoCtxMenu menu) {
		menu.setOnClickListener(new IcoCtxMenu.IconContextMenuOnClickListener() {
			@Override
			public void onClick(int menuId) {
					switch (menuId) {
					case MENUCTX_ITEM_MODIFY:
						showDialog(DIALOG_MODIFY);
						break;
					case MENUCTX_ITEM_REFRESH:
						feedBurnPI.putExtra("qid", fq.get(ctxMenuItemPos).getQid());
						startService(feedBurnPI);
						break;
					case MENUCTX_ITEM_DELETE:
						showDialog(DIALOG_DELETE);
						break;
					case MENUCTX_ITEM_MOREI:
						removeDialog(DIALOG_MOREI);
						showDialog(DIALOG_MOREI);
						break;
					}
			}

		});
	}
	
	//TODO: verificarne lo spreco di risorse
	private void fillList(String order){
		if (order == null)
			order=qOrder;
		
    	db.openR();
		fq = db.fillQuerys(order);
		listAdapter = new AdapterList(this, fq);
		setListAdapter(listAdapter);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		qOrder = prefs.getString("view_querys_order", "last DESC");
		iOrder = prefs.getString("view_items_order", "pub_date DESC");
		//Log.d(LOG_TAG,"iorder:"+iOrder+" qorder:"+qOrder);
		
		if (db == null)
			db = new DbFeed(getApplicationContext());
		
		fillList(null);
		
    	icoCtxMenu = new IcoCtxMenu(this, CTX_MENU_ID);
		fillContextMenus();
		setCallbackContextMenu(icoCtxMenu);
		getListView().setOnItemLongClickListener(listItemLongClickHandler);
	}
	
	private OnItemLongClickListener listItemLongClickHandler = new OnItemLongClickListener() {
		@Override
		public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
			Log.i(LOG_TAG, "gridItLongClick");
			ctxMenuItemPos = position;
			showDialog(CTX_MENU_ID);
			return true;
		}
	};
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Log.i(LOG_TAG, "onCreateDialog() pos:"+ctxMenuItemPos);
		switch (id) {
			case CTX_MENU_ID:
				dialog = icoCtxMenu.createMenu(
					R.string.app_menu+fq.get(ctxMenuItemPos).getTitle(), 
						R.drawable.query_bookmark);
				break;
			case DIALOG_MODIFY:
				dialog = modifyDialog();
				break;
			case DIALOG_MOREI:
				dialog = SDialog.moreiDialog(this,fq.get(ctxMenuItemPos));
				break;
			case DIALOG_DELETE:
				dialog = deleteDialog();
				break;
		}

		return dialog;
	}
	
	private Dialog deleteDialog(){
        AlertDialog dialog = new AlertDialog.Builder(this)
        .setIcon(R.drawable.delete)
        .setTitle(R.string.diag_delete_title)
        .setView(SDialog.setSimpleTV(getBaseContext(), R.string.diag_delete_msg))
        .setPositiveButton(R.string.diag_delete_yesbtn, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
				db.openW();
				db.deleteQuery(fq.get(ctxMenuItemPos));
				fq.remove(ctxMenuItemPos);
				listAdapter.notifyDataSetInvalidated();
				fillList(null);
				Toast.makeText(getBaseContext(), R.string.toast_delete_ok, Toast.LENGTH_SHORT).show();
            	removeDialog(DIALOG_DELETE);
            }
        })
        .setNegativeButton(R.string.diag_delete_nobtn, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	removeDialog(DIALOG_DELETE);
            }
        }).create();
        
        return dialog;
	}
	
	private Dialog modifyDialog(){
		FeedQuery q = fq.get(ctxMenuItemPos);
		final int qid = q.getQid();
        LayoutInflater factory = LayoutInflater.from(this);
        final View textEntryView = factory.inflate(R.layout.dialog_modify, null);
        final EditText title_et = (EditText) textEntryView.findViewById(R.id.modify_title_et); 
        final EditText desc_et = (EditText) textEntryView.findViewById(R.id.modify_desc_et);
        
        title_et.setText(q.getTitle());
        desc_et.setText(q.getDesc());
        AlertDialog dialog = new AlertDialog.Builder(this)
        .setIcon(R.drawable.modify)
        .setTitle(R.string.diag_modify_title)
        .setView(textEntryView)
        .setPositiveButton(R.string.diag_modify_yesbtn, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	db.openW();
            	db.updateModifyQuery(title_et.getText().toString(), desc_et.getText().toString(), qid);
            	fillList(null);
            	removeDialog(DIALOG_MODIFY);
            }
        })
        .setNegativeButton(R.string.diag_modify_nobtn, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            	removeDialog(DIALOG_MODIFY);
            }
        }).create();
        
        return dialog;
	}

    public boolean onCreateOptionsMenu(Menu menu) {

    	super.onCreateOptionsMenu(menu);

        menu.add(Menu.CATEGORY_ALTERNATIVE, MENU_REFRESH_ID, 0, R.string.menu_arch_refresh)
        	.setOnMenuItemClickListener(menuItemClickHandler)
        	.setIcon(R.drawable.ic_menu_refresh);
        SubMenu subMenu = 
        	menu.addSubMenu(Menu.CATEGORY_ALTERNATIVE, MENU_ORDER_ID, 0, R.string.menu_arch_ord)
    			.setIcon(R.drawable.ic_menu_order)
    			.setHeaderIcon(R.drawable.ic_menu_order)
    			.setHeaderTitle(R.string.submenu_arch_ord);
        String order[] = res.getStringArray(R.array.view_querys_order);
        for(int i=0;i<order.length;i++){
        	//TODO: trovare icone
        	subMenu.add(0,i,i,order[i]);
        }
        
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	String order[] = res.getStringArray(R.array.view_querys_order);
    	String order_value[] = res.getStringArray(R.array.view_querys_order_value);
    	for(int i=0;i<order.length;i++){
    		if(item.getItemId()==i){
    			fillList(order_value[i]);
    			break;
    		}
    	}
    	
    	return super.onOptionsItemSelected(item);
    }
    
	private OnMenuItemClickListener menuItemClickHandler = new OnMenuItemClickListener() {
		
		@Override
		public boolean onMenuItemClick(MenuItem item) {
			switch (item.getItemId()) {
					case MENU_REFRESH_ID:
						ATab.feedBurnI.putExtra("stop", true);
						startService(ATab.feedBurnI);
						break;
					default:
			}
			
			return true;
		}
	};

    @Override
	public void onBackPressed() {  
		RssReader.setFromState(RssReader.STATE_BACK_VIEWER);
		super.onBackPressed();
		
	    return;  
	}  
	
    @Override
    protected void onPause() {
    	super.onPause();
    	db.close();
    }
}
