package com.wasu.cs.ui;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * Created by LiuYang on 7/10/15.
 */
public abstract class FragmentChannelBase extends Fragment {

    LayoutInflater mInflater;
    Handler mHandler = new Handler();

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        
        try {
			backHandlerInterface = (BackHandlerInterface) activity;
		} catch (Exception e) {
			throw new ClassCastException("Hosting activity must implement BackHandlerInterface");
		}
    }
    
    @Override
    public void onDetach() {
    	super.onDetach();
    	
    	backHandlerInterface = null;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        this.mInflater = inflater;
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    public void addToBackPressed() {
    	if (backHandlerInterface == null) {
    		return;
    	}
    	
        backHandlerInterface.setSelectedFragment(this);
    }


    public int getDimenPixel(int id) {
        return getResources().getDimensionPixelSize(id);
    }

    public LayoutInflater getInflater() {
        return mInflater;
    }

    public Handler getHandler() {
        return mHandler;
    }

    protected abstract boolean onBackPressed();

    protected BackHandlerInterface backHandlerInterface;
    public interface BackHandlerInterface {
        public void setSelectedFragment(FragmentChannelBase backHandledFragment);
    }
    
    @Override
    public void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	if(mInflater != null){
    		mInflater = null;
    	}
    	if(mHandler != null){
    		mHandler.removeCallbacksAndMessages(null);
    	}
    }
}
