package com.wasu.cs.ui;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.imagepipeline.image.CloseableBitmap;
import com.facebook.imagepipeline.image.CloseableStaticBitmap;
import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.authsdk.IAuthInterface;
import com.wasu.common.WError;
import com.wasu.cs.module.ScreenSaverModule;
import com.wasu.cs.utils.ActivityManager;
import com.wasu.cs.utils.BitmapUtils;
import com.wasu.cs.utils.HomeListener;
import com.wasu.cs.widget.ActivityLiveVideoView;
import com.wasu.cs.widget.ErrorDialog;
import com.wasu.frescoimagefetchermodule.FrescoImageFetcherModule;
import com.wasu.frescoimagefetchermodule.ImageFetchListener;
import com.wasu.module.log.WLog;
import com.wasu.statistics.StatisticsConstant;
import com.wasu.statistics.WasuStatistics;
import com.wasu.util.NetUtils;

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

import basic.app.TvAppLike;
import cn.com.wasu.main.AppUtil;
import cn.com.wasu.main.AppUtil.OnNetStateListener;
import cn.com.wasu.main.BuildConfig;
import cn.com.wasu.main.IntentConstant;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

/**
 * 基类，所有activity都基于这个类
 *
 * @author Administrator
 */
public abstract class ActivityBase extends FragmentActivity implements OnNetStateListener {
    private final String TAG = this.getClass().getSimpleName();
    public static final int AUTH_CHECK_YES = 1;
    public static final int AUTH_CHECK_NO = 2;
    public static final int AUTH_CHECK_CANCEL = 3;
    public static final int AUTH_CHECK_EXIT = 4;

    private Bundle mSaveStateBackup;

    private ViewGroup mLoadingView;

    /**
     * 网络错误警告框
     */
    private ErrorDialog mDlgNetWarning;

    /**
     * 网络错误警告框
     */
    private ErrorDialog mDlgNetError;

    /**
     * 统一推出错误对话框
     */
    private ErrorDialog mDlgError;

    DataSource mDataSource = null;
    CloseableReference mReference = null;
    CloseableBitmap mImage = null;

    private HomeListener mHomeWatcher;

//	public static String bgPic;

    /**
     * 延迟create
     *
     * @param savedInstanceState
     */
    protected abstract void doCreate(Bundle savedInstanceState);

    /* (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSaveStateBackup = savedInstanceState;
        ActivityManager.getInstance().addActivity(this);
        Log.i(getClass().getSimpleName(), "Msg:onCreate");
        setDefaultBg(null);

        initLoading();

        if (!checkNetConnect()) {
            showNetError();
            return;
        }

        //网络状态监测
        AppUtil.addOnNetStateListener(this);

        int authCheck = checkAuthState();
        if (authCheck == AUTH_CHECK_NO) {
            doAuth();
            return;
        } else if (authCheck == AUTH_CHECK_EXIT) {
            return;
        }
        //每个页面都添加TVID属性
        Map<String, String> map = new HashMap<String, String>();
        map.put(StatisticsConstant.TVID, AuthSDK.getInstance().getValue(IAuthInterface.KEY_TVID));
        WasuStatistics.getInstance().addPageElem(map);
        //完成对应view的初始化
        doCreate(savedInstanceState);

        registerHomeListener();
    }

    private void registerHomeListener() {
        mHomeWatcher = new HomeListener(this);
        mHomeWatcher.setOnHomePressedListener(new HomeListener.OnHomePressedListener() {

            @Override
            public void onHomePressed() {
                //TODO 进行点击Home键的处理
                if (BuildConfig.FLAVOR.equals("BenQ")) {
                    ScreenSaverModule.getInstance().clearTask();
                    ActivityManager.getInstance().exitApp();
                    TvAppLike.getInstance().onTerminate();
                    System.exit(0);
                }
            }

            @Override
            public void onHomeLongPressed() {
                //TODO 进行长按Home键的处理
            }
        });
        mHomeWatcher.startWatch();
    }

    /**
     * fresco加载的背景 释放资源
     */
    private void releaseBgRes() {
        if (mImage != null) {
            mImage.close();
            mImage = null;
        }
        if (mReference != null) {
            CloseableReference.closeSafely(mReference);
            mReference = null;
        }
        if (mDataSource != null) {
            mDataSource.close();
            mDataSource = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().removeActivity(this);

        releaseBgRes();

        hideErrorExitDlg();

        hideNetWarning();

        if (mDlgNetError != null) {
            mDlgNetError.dismiss();
            mDlgNetError = null;
        }
    }

    /*
     * 为了使loading一直在上面显示
     */
    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        getWindow().addContentView(mLoadingView, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    }

    /*
     * 为了使loading一直在上面显示
     */
    @Override
    public void addContentView(View view, LayoutParams params) {
        if (mLoadingView.getParent() != null) {
            ((ViewGroup) mLoadingView.getParent()).removeView(mLoadingView);
        }
        super.addContentView(view, params);
        getWindow().addContentView(mLoadingView, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    }

    /**
     * 初始化统一loading框
     */
    private void initLoading() {
        mLoadingView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.base_loading, null);
        getWindow().addContentView(mLoadingView, new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    }


    /**
     * 设置统一背景
     */
    protected void setDefaultBg(Drawable drawable) {
        if (drawable != null) {
            getWindow().setBackgroundDrawable(drawable);
            return;
        }
        SharedPreferences sp = getApplicationContext().getSharedPreferences("deviceData", Context.MODE_PRIVATE);
        if (!sp.getBoolean("isHighDevice", true)) {
            getWindow().setBackgroundDrawableResource(R.color.main_bg);
        } else {
            Bitmap bitmap = BitmapUtils.readBitMapByDecodeStream(this, R.drawable.main_home_bg, Bitmap.Config.ARGB_8888);
            getWindow().setBackgroundDrawable(new BitmapDrawable(getResources(), bitmap));
        }
    }

    /**
     * @param resourseId
     */
    protected void setBg(int resourseId) {
        SharedPreferences sp = getApplicationContext().getSharedPreferences("deviceData", Context.MODE_PRIVATE);
        if (!sp.getBoolean("isHighDevice", true)) {
            getWindow().setBackgroundDrawableResource(R.color.main_bg);
        } else {
            getWindow().setBackgroundDrawableResource(resourseId);
        }
    }

    /**
     * 设置背景
     */
    public void setBg(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        FrescoImageFetcherModule.getInstance().loadImage(url, new ImageFetchListener() {
            @Override
            public void onFetchAdded(String imgUrl) {

            }

            @Override
            public void onFetchCancelled(String imgUrl) {

            }

            @Override
            public void onFetchFailed(String imgUrl, Throwable throwable) {

            }

            @Override
            public void onFetchCompleted(String imgUrl, DataSource dataSource) {
                mDataSource = dataSource;
                mReference = (CloseableReference) mDataSource.getResult();
                mImage = (CloseableStaticBitmap) mReference.get();
                Bitmap bm = mImage.getUnderlyingBitmap();
                if (bm != null) {
                    Drawable drawable = new BitmapDrawable(getResources(), bm);
                    getWindow().setBackgroundDrawable(drawable);
                }
            }
        });
    }

    /**
     * 检查授权状态
     *
     * @return
     */
    protected int checkAuthState() {
        if (AuthSDK.getInstance().isDeviceLogin()) {
            return AUTH_CHECK_YES;
        } else {
            return AUTH_CHECK_NO;
        }
    }

    /**
     * 检查网络状态
     *
     * @return
     */
    protected boolean checkNetConnect() {
        return NetUtils.isNetConnected(TvAppLike.getContext());
    }

    protected void doAuth() {
        final AuthListener loginListener = new AuthListener() {

            @Override
            public void result(int arg0, String arg1, Object arg2) {
                hideLoading();
                String success = "0";
                if (arg0 == WError.ERROR_NONE) {
                    doCreate(mSaveStateBackup);
                    success = "1";
                } else {
                    success = "0";
                    if (arg0 == WError.ERROR_UPM_NOT_AUTH) {
                        IntentMap.startIntent(ActivityBase.this, null, null, null, ActivityServiceStop.class);
                        finish();
                        return;
                    } else {
                        showAuthError(arg1);
                    }
                }
                WasuStatistics.getInstance().loadEnd(success);
            }
        };

        final AuthListener RegisterListener = new AuthListener() {
            @Override
            public void result(int arg0, String arg1, Object arg2) {
                String success = "0";
                if (arg0 == WError.ERROR_NONE) {
                    AuthSDK.getInstance().deviceLogin(loginListener);
                    success = "1";
                } else {
                    success = "0";
                    if (arg0 == WError.ERROR_UPM_NOT_AUTH) {
                        IntentMap.startIntent(ActivityBase.this, null, null, null, ActivityServiceStop.class);
                        finish();
                        return;
                    } else {
                        showAuthError(arg1);
                    }

                }
                WasuStatistics.getInstance().registEnd(success);
            }
        };

        showLoading();
        if (!AuthSDK.getInstance().isDeviceRegister()) {
            WasuStatistics.getInstance().registBegin();
            AuthSDK.getInstance().deviceRegister(RegisterListener);
        } else if (!AuthSDK.getInstance().isDeviceLogin()) {
            WasuStatistics.getInstance().loadBegin();
            AuthSDK.getInstance().deviceLogin(loginListener);
        } else {
            doCreate(mSaveStateBackup);
        }
    }

    public void hideErrorExitDlg() {
        if (mDlgError != null) {
            mDlgError.dismiss();
            mDlgError = null;
        }
    }

    /**
     * 统一的错误退出对话框
     *
     * @param msg
     */
    public void showErrorExitDlg(String msg) {
        hideLoading();

        hideErrorExitDlg();

        if (isFinishing()) {
            return;
        }

        mDlgError = new ErrorDialog.mBuilder(this).setMessage(msg)
                .addBtn1("退出", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mDlgError = null;
                        finish();
                    }
                }).addBtn2("我要反馈", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mDlgError.feedBack(2);
                    }
                }).create();

        mDlgError.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                mDlgError = null;
                finish();
            }
        });
        mDlgError.show();
    }

//	/**
//	 * 授权出错
//	 * @param msg
//	 */
//	private void showAuthError(String msg){
//		hideLoading();
//		Dialog dlgAuth = new ErrorDialog.mBuilder(this)
//							.setTitle("授权出错")
//							.setMessage("当前设备未成功认证，请稍后重试")
//							.addBtn1("退出", new OnClickListener() {
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				finish();
//			}
//		}).create();
//		
//		dlgAuth.setCancelable(false);
//		dlgAuth.show();
//	}

    /**
     * 授权出错
     *
     * @param msg
     */
    private void showAuthError(String msg) {
        hideLoading();
        if (!isFinishing()) {
            Dialog dlgAuth = new ErrorDialog.mBuilder(this)

                    .setMessage(msg + "!如有疑问，请联系客服")
                    .addBtn1("退出", new android.content.DialogInterface.OnClickListener() {


                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            finish();

                        }
                    }).addBtn2("重试", new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {
                            doAuth();

                        }
                    }).create();

            dlgAuth.setCancelable(false);
            dlgAuth.show();
        }
    }

    /**
     * 隐藏网络提醒
     */
    private void hideNetWarning() {
        if (mDlgNetWarning != null) {
            mDlgNetWarning.dismiss();
            mDlgNetWarning = null;
        }
    }

    /**
     * 网络断开提醒
     */
    private void showNetWarning() {
        hideNetWarning();
        if (mDlgError != null || mDlgNetError != null) {
            return;
        }

        mDlgNetWarning = new ErrorDialog.mBuilder(this)
                .setTitle("网络错误")
                .setMessage("当前网络已断开")
                .addBtn1("知道了", null).addBtn2("我要反馈", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mDlgNetWarning.feedBack(2);
                    }
                }).create();
        mDlgNetWarning.show();
    }

    /**
     * 网络出错
     */
    private void showNetError() {
        if (mDlgNetError != null) {
            mDlgNetError.dismiss();
            mDlgNetError = null;
        }

        mDlgNetError = new ErrorDialog.mBuilder(this)
                .setTitle("网络错误")
                .setMessage("当前网络未连接")
                .addBtn1("退出", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).addBtn2("我要反馈", new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mDlgNetError.feedBack(2);
                    }
                }).create();

        mDlgNetError.setOnCancelListener(new OnCancelListener() {

            @Override
            public void onCancel(DialogInterface dialog) {
                finish();
            }
        });

        mDlgNetError.show();
    }

    /**
     * 显示loading框
     */
    public void showLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示loading框
     */
    public void showLoading(int textColor) {
        if (mLoadingView != null) {
            ((TextView) mLoadingView.findViewById(R.id.base_loading_text)).setTextColor(textColor);
            mLoadingView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏loading框
     */
    public void hideLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
        }
    }

    public void cleanLoading() {
        if (mLoadingView != null) {
            mLoadingView.removeAllViews();
            mLoadingView = null;
        }
    }

    /**
     * 显示toast信息
     */
    protected void postMessage(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        WLog.e("ActivityBase", "[" + message + "]");
    }

    @Override
    public void onStateChanged(int state) {
        if (AppUtil.ETHERNET_DISCONNECTED == state || AppUtil.WIFI_DISCONNECTED == state) {
            showNetWarning();
        } else {
            hideNetWarning();
        }
    }

    /**
     * 回到首页
     */
    private void goHomePage() {
        try {
            Intent intent = new Intent(this, ActivityMain.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        ScreenSaverModule.getInstance().updateUserActionTime();
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    public void finish() {
        super.finish();
        //移除网络状态监听
        AppUtil.removeOnNetStateListener(this);

        /** 外调回到首页 **/
        if (getIntent() != null && getIntent().getBooleanExtra(IntentConstant.BACK_MAIN.value(), false)) {
            goHomePage();
        }

        if (!(this instanceof ActivityPlayer) || !(this instanceof ActivityLiveVideoView)) {
            overridePendingTransition(R.anim.activity_up_in, R.anim.activity_up_out);
        }
    }
}
