package hh.dejsem.clipboard;

import android.os.Bundle;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.text.DateFormat;
import java.util.Comparator;
import java.util.HashMap;
import java.util.TreeMap;

import hh.dejsem.K;
import hh.dejsem.R;
import hh.dejsem.net.SrvCmd;
import hh.lib.D;
import hh.lib.DF;

/**
 * manages clipboard history list
 */
public class HistFrag extends DF {

	final String TITLETEXT = "clipboard";

	public static interface Listener { void getHistEntry(String entry); }

	public static HistFrag instantiate(D d/*, Listener listener*/) {
		HistFrag hf = new HistFrag();
		hf.d = d.klon(hf);
//		hf.listener = listener;
		return hf;
	}

	HistList histlist;
	View histView = null;
	Listener listener;
	K.HistOrder order = K.HistOrder.TEXT;
	boolean ascending = true;
	TextView sText, sSize, sDate;
	View.OnClickListener sortByText, sortBySize, sortByDate;
//	View.OnClickListener lastMile;
	AdapterView.OnItemClickListener clickEntry = null;
//	HistAct.HistListAdapter histListAdapter;
	ListView lh = null;

	/*@Override
	public void onCreate(Bundle b) {
		super.onCreate(b);
	}*/

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle b) {
		super.onCreate(b);
		/*if(K.histlist != null) */histView = inflater.inflate(R.layout.hist_list, null);
		return histView;
	}

	@Override
	public void onViewStateRestored(Bundle b) {
		super.onViewStateRestored(b);
		listener = (HistFrag.Listener)getActivity();
	}

	@Override
	public void onStart() {
		super.onStart();
		pullHistList();

		sText = (TextView)histView.findViewById(R.id.sText);
		sortByText = new View.OnClickListener() { @Override public void onClick(View v) { sortHistList(K.HistOrder.TEXT); } };
		sText.setOnClickListener(sortByText);
		sSize = (TextView)histView.findViewById(R.id.sSize);
		sortBySize = new View.OnClickListener() { @Override public void onClick(View v) { sortHistList(K.HistOrder.SIZE); } };
		sSize.setOnClickListener(sortBySize);
		sDate = (TextView)histView.findViewById(R.id.sDate);
		sortByDate = new View.OnClickListener() { @Override public void onClick(View v) { sortHistList(K.HistOrder.DATE); } };
		sDate.setOnClickListener(sortByDate);

		clickEntry = new AdapterView.OnItemClickListener() {
			@Override public void onItemClick(AdapterView<?> parent, View v, int pos, long id) { getHistItem(pos); } };
		lh = (ListView)histView.findViewById(R.id.listHist);
		lh.setOnItemClickListener(clickEntry);

		sortHistList(K.HistOrder.DATE, false);
	}

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

	@Override
	public void onResume() {
		super.onResume();
		K.title.setText(TITLETEXT).update();
	}

	void pullHistList() {
		if(histlist == null)
			try { histlist = (HistList)SrvCmd.PULLHIST.exec(d, null); }
			catch(Exception e) {
				d.abendMsg("clipboard history", e);
				histlist = null;
			}
	}

	void dispHistList() {
		sText.setCompoundDrawablesWithIntrinsicBounds(0,0,0,0);
		if(order == K.HistOrder.TEXT)
			sText.setCompoundDrawablesWithIntrinsicBounds((ascending ? R.drawable.asc : R.drawable.desc),0,0,0);
		sSize.setCompoundDrawablesWithIntrinsicBounds(0,0,0,0);
		if(order == K.HistOrder.SIZE)
			sSize.setCompoundDrawablesWithIntrinsicBounds((ascending ? R.drawable.asc : R.drawable.desc),0,0,0);
		sDate.setCompoundDrawablesWithIntrinsicBounds(0,0,0,0);
		if(order == K.HistOrder.DATE)
			sDate.setCompoundDrawablesWithIntrinsicBounds((ascending ? R.drawable.asc : R.drawable.desc),0,0,0);

		lh.setAdapter(new HistListAdapter(d, histlist));
	}

	void getHistItem(int pos) {
		String entry = histlist.entries.get(histlist.list.get(pos)).name;
		listener.getHistEntry(entry);
		getActivity().getSupportFragmentManager().popBackStack();
	}

	void sortHistList(K.HistOrder order) {
		ascending = !ascending;
		sortHistList(order, ascending);
	}

	void sortHistList(K.HistOrder order, boolean ascending) {
		this.order = order;
		this.ascending = ascending;
		TreeMap<String, HistList.HistEntry> tree = new TreeMap<>(new HistEntryComparator(d, histlist.entries, order, ascending));
		for(HistList.HistEntry e: histlist.entries.values()) tree.put(e.name, e);
		histlist.list = HistList.allocList(tree.keySet());
		if(lh != null ) lh.setAdapter(new HistListAdapter(d, histlist));
		dispHistList();
	}

	/**
	 * adapter for history list ordering
	 */
	static class HistEntryComparator implements Comparator<String> {
		D d;
		HashMap<String, HistList.HistEntry> map;
		K.HistOrder order;
		int direction = 1;

		HistEntryComparator(D d, HashMap<String, HistList.HistEntry> map, K.HistOrder order, boolean ascending) {
			this.d = d.klon("comparator");
			this.map = map;
			this.order = order;
			if(!ascending) direction *= -1;
		}

		@Override
		public int compare(String l, String r) {
			try {
				switch(order) {
				case TEXT:
					if(map.get(l).text.equals(map.get(r).text)) return l.compareTo(r) * direction;
					else return map.get(l).text.compareTo(map.get(r).text) * direction;
				case SIZE:
					if(map.get(l).size == map.get(r).size) return l.compareTo(r) * direction;
					else return Long.valueOf(map.get(l).size).compareTo(map.get(r).size) * direction;
				case DATE:
					if(map.get(l).date == map.get(r).date) return l.compareTo(r) * direction;
					else return Long.valueOf(map.get(l).date).compareTo(map.get(r).date) * direction;
				default: return 0;
				}
			}
			catch(Exception e) { d.abendMsg("compare", e); throw new Error(); }
		}
	}

	/**
	 * adapter for histlist list display
	 */
	static class HistListAdapter extends BaseAdapter {
		D d;
		HistList history;
		HistList.HistEntry item;
		CheckBox chkbox;
		ImageView icon;
		TextView text, size, date;
		LayoutInflater li;
		DateFormat df;
		boolean go = true;
		/* ----------------------------------------------------------*/

		HistListAdapter(D d, HistList history) {
			this.d = d.klon("histview adapter");
			this.history = history;
			li = LayoutInflater.from(d.getContext());
			df = android.text.format.DateFormat.getDateFormat(d.getContext());
		}

		public int getCount() { return history.list.size(); }

		public Object getItem(int position) { return null; }

		public long getItemId(int position) { return 0; }

		public int getViewTypeCount() { return 1; }

		public View getView(int position, View listEntry, ViewGroup parent) {
			RelativeLayout v;
			v = (RelativeLayout)(listEntry == null ? li.inflate(R.layout.hist_entry, null) : listEntry);
			v.setId(position);

			item = history.entries.get(history.list.get(position));

			text = (TextView)(v.findViewById(R.id.htext));
			text.setText(item.text);

			size = (TextView)(v.findViewById(R.id.hsize));
			size.setText(String.format(" %8s ", Formatter.formatFileSize(d.getContext(), item.size)));

			date = (TextView)(v.findViewById(R.id.hdate));
			date.setText(df.format(item.date * 1000));

			return v;
		}
	}
}



