package com.wasu.cs.ui;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;

import com.wasu.common.WError;
import com.wasu.cs.model.CatData;
import com.wasu.cs.module.WasuCacheModule;
import com.wasu.cs.protocol.CatProtocol;
import com.wasu.module.log.WLog;
import com.wasu.statistics.StatisticsConstant;
import com.wasu.statistics.WasuStatistics;

import java.util.HashMap;
import java.util.Map;

import cn.com.wasu.main.ErrorMap;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.R;

/**
 * 资产二级列表
 * Created by LiuYang on 6/18/15.
 */
public class ActivityChannel extends ActivityBase implements FragmentChannelBase.BackHandlerInterface {
    private String TAG = "ActivityChannel";

    private FragmentChannelBase selectedFragment;

    private FragmentBlockChannel mFragment;
//    private Handler mHandler = new Handler();
//    private String CAT_URL = "http://121.40.195.74/?s=2002&p=sntCat&k=1&v=1&catId=297368";//movie
//    private String CAT_URL = "http://121.40.195.74/?s=2002&p=sntCat&k=1&v=1&catId=274982";
    private String CAT_URL = "http://121.40.195.74/?s=2002&p=sntCat&k=1&v=1&catId=297448"; //news
//    private String CAT_URL = "http://121.40.195.74/?s=2002&p=sntCat&k=1&v=1&catId=297440";//music
//    private String CAT_URL = "http://121.40.195.74/?s=2002&p=sntCat&k=1&v=1&catId=297430"; //entertainment

    private CatData catDataBackup; // 记录数据
    private String mSelectedPage=""; // 当前选中的二级列表标题
    private static final String PageViewType = "column";

    @Override
    protected void doCreate(Bundle savedInstanceState) {
        WLog.i(TAG,"doCreate()");
//        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
//            finish();
//            return;
//        }


    	FragmentFactory.clearCache();
        setContentView(R.layout.activity_channel);

        CAT_URL = getIntent().getStringExtra(IntentConstant.DATAURI.value());

        if(TextUtils.isEmpty(CAT_URL)) {
            showErrorExitDlg(ErrorMap.mapError(this, WError.ERROR_UNSUPPORT, null));
            return;
        }
        mFragment = (FragmentBlockChannel) getSupportFragmentManager().findFragmentById(R.id.fragment);
        requestData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        WasuStatistics.getInstance().pageViewStart(PageViewType);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(catDataBackup!=null)
        WasuStatistics.getInstance().pageViewEnd(PageViewType, catDataBackup.getCat().getName(), mSelectedPage);
    }

    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	FragmentFactory.clearCache();
    	cleanResource();
    }

    @Override
    public void onBackPressed() {
        if(selectedFragment == null || !selectedFragment.onBackPressed()){
            if(getSupportFragmentManager().getBackStackEntryCount() == 0){
            	FragmentFactory.clearCache();
                super.onBackPressed();
            }else{
                getSupportFragmentManager().popBackStack();
            }
        }
    }

    private void cleanResource(){
    	if(selectedFragment != null){
    		selectedFragment = null;
    	}
    	if(mFragment != null){
    		mFragment.cleanResource();
    		mFragment = null;
    	}
    	ViewGroup group = (ViewGroup) this.getWindow().getDecorView().getRootView();
	    group.removeAllViews();
	    group.destroyDrawingCache();
	    group = null;
	    cleanLoading();
    }
    
    private void requestData() {
    	showLoading();
        CatData mCatData = (CatData) WasuCacheModule.getInstance().getAsObject(CAT_URL);
        if(mCatData != null){
            mFragment.initData(mCatData);
            catDataBackup = mCatData;
            hideLoading();
            //添加栏目名称
            Map<String, String> map=new HashMap<String, String>();
            map.put(StatisticsConstant.CAT_ID, "");
            map.put(StatisticsConstant.CAT_NAME, mCatData.getCat().getName());
            WasuStatistics.getInstance().addPageElem(map);

            CatProtocol.fetchData(null, CAT_URL, new CatProtocol.CatFetchCallback() {
                @Override
                public void onResult(boolean successed, CatData catData) {
                    if (successed) {
                        WasuCacheModule.getInstance().remove(CAT_URL);
                        WasuCacheModule.getInstance().put(CAT_URL ,catData);
                    } else {
                        showErrorExitDlg(ErrorMap.mapError(ActivityChannel.this, WError.ERROR_NET, null));
                    }
                }
            });
        }else{
            CatProtocol.fetchData(null, CAT_URL, new CatProtocol.CatFetchCallback() {
                @Override
                public void onResult(boolean successed, CatData catData) {
                    hideLoading();
                    if (successed) {
                        mFragment.initData(catData);
                        catDataBackup = catData;
                        WasuCacheModule.getInstance().remove(CAT_URL);
                        WasuCacheModule.getInstance().put(CAT_URL, catData);
                        //添加栏目名称
                        Map<String, String> map=new HashMap<String, String>();
                        map.put(StatisticsConstant.CAT_ID, "");
                        map.put(StatisticsConstant.CAT_NAME, catData.getCat().getName());
                        WasuStatistics.getInstance().addPageElem(map);
                    } else {
                        showErrorExitDlg(ErrorMap.mapError(ActivityChannel.this, WError.ERROR_NET, null));
                    }
                }
            });
        }

    }

    @Override
    public void setSelectedFragment(FragmentChannelBase backHandledFragment) {
        this.selectedFragment = backHandledFragment;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    public void setViewName(String view){
        mSelectedPage = view;
    }
}
