package com.wasu.cs.ui;

import java.lang.ref.WeakReference;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import cn.com.wasu.main.R;

public class DialogWithHistory extends Dialog {
	private WeakReference<onChoiceListener> mChoiceListener;
	private int 	mLastSeries;
	private long 	mLastPlayMs;
	private boolean isSeries;

	public static final int GOON = 1;
	public static final int REDO = 2;
	
	public interface onChoiceListener{
		public void onChoice(int choice);
	}
	
	public DialogWithHistory(Context context, int lastSeries, long lastPlayMs, onChoiceListener l, boolean isSeries) {
		super(context, R.style.dialog);
		
		mChoiceListener = new WeakReference<onChoiceListener>(l);
		mLastSeries = lastSeries;
		mLastPlayMs = lastPlayMs;
		this.isSeries = isSeries;
		
		init(context);
	}

	private void doChoice(int choice){
		if (mChoiceListener.get() != null){
			mChoiceListener.get().onChoice(choice);
		}
	}
	
	private String getTimeText(long playMs){
		playMs = (playMs + 1000) / 1000;
		long second = playMs % 60;
		long minute = playMs / 60 % 60;
		long hour   = playMs / 3600;
		
		if (hour > 0){
			return String.format(getContext().getString(R.string.time_h), hour, minute, second);
		}else if(minute > 0){
			return String.format(getContext().getString(R.string.time_m), minute, second);
		}else{
			return String.format(getContext().getString(R.string.time_s), second);
		}
	}
	
	private String getSeries(int series){
		if (series > 0){
			return String.format(getContext().getString(R.string.series_num), series);
		}else{
			return "";
		}
	}
	
	private void init(Context context) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.dialog_with_history);
		
		TextView tvHistory 	= (TextView) findViewById(R.id.tvHistory);
		Button btnGoon 		= (Button) findViewById(R.id.goon);
		Button btnRedo 		= (Button) findViewById(R.id.redo);
		
		if (isSeries) {
			btnRedo.setText(context.getString(R.string.play_redo_series));
		}
		
		btnGoon.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				doChoice(GOON);
				dismiss();
			}
		});
		btnRedo.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				doChoice(REDO);
				dismiss();
			}
		});
		
		if (isSeries) {
			tvHistory.setText(String.format(getContext().getString(R.string.play_history), getSeries(mLastSeries + 1), getTimeText(mLastPlayMs)));
		} else {
			tvHistory.setText(String.format(getContext().getString(R.string.play_history), getSeries(mLastSeries), getTimeText(mLastPlayMs)));
		}
	}
}
