package com.sheep.gamegroup.view.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.kfzs.appstore.utils.restful.KFZSNetwork;
import com.kfzs.duanduan.ActDownloadMgr;
import com.kfzs.duanduan.ActGameDetails;
import com.kfzs.duanduan.ActSearch;
import com.kfzs.duanduan.KFZSApp;
import com.kfzs.duanduan.bean.KFIntentKeys;
import com.kfzs.duanduan.bll.UrlBll;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfo;
import com.kfzs.duanduan.db.DataSave;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventTypes;
import com.kfzs.duanduan.fragment.FgtMainGame;
import com.kfzs.duanduan.proto.ApiResponseOuterClass;
import com.kfzs.duanduan.proto.GameOuterClass;
import com.kfzs.duanduan.proto.RecommendedGameOuterClass;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.kfzs.duanduan.utils.dlg.SkipUtils;
import com.kfzs.duanduan.utils.net.APIRequest;
import com.kfzs.duanduan.utils.net.APIRequestInstance;
import com.kfzs.duanduan.utils.net.ResponseNetworkTask;
import com.kfzs.duanduan.view.AppHomepageAdvertisementDialog;
import com.kfzs.duanduan.view.DialogStorageLow;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;

import static com.kfzs.duanduan.services.DownloadTaskService.STATUS_ING;

/**
 * Created by ljy on 2018/5/10.
 */

public class ActMainGame extends BaseActivity {

    @BindView(R.id.layout_main_activity_toolbar)
    View layout_main_activity_toolbar;
    @BindView(R.id.download_layout)
    View download_layout;
    @BindView(R.id.edt_main_search_enter)
    EditText edt_main_search_enter;
    @BindView(R.id.img_download_manager_dot)
    ImageView mImgDot;//下载按钮的小红点
    Activity activity;


    private static final String TAG = "ActMainGame";
    private DownloadTaskService mDownloadTaskService;

    private AppHomepageAdvertisementDialog gameDialog;//预约窗口
    private boolean isGetAdvertisementDialogData = false;

    @Override
    protected int getLayoutId() {
        return R.layout.act_main_game;
    }

    @Override
    public void initView() {

        activity = this;

        EventBus.getDefault().register(this);
        mDownloadTaskService = new DownloadTaskService(this);
        TitleBarUtils
                .getInstance()
                .setTitle(this, "玩转游戏")
                .setTitleFinish(this)
                .setRightImgBotton(activity, R.drawable.index_download, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(activity, ActDownloadMgr.class));
//                        mImgDot.setVisibility(View.GONE);
                        TitleBarUtils.getInstance()
                                .setRightRedPoint(activity, View.GONE);
                        UMConfigUtils.onEvent(UMConfigUtils.Event.GAME_DOWNLOAD_MANAGER);
                    }
                });
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Bundle bundle = new Bundle();
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("tag");
        if (fragment == null) {
            fragment = new FgtMainGame();
            fragment.setArguments(bundle);
            transaction.add(R.id.frame_container, fragment, "tag");
            transaction.commitAllowingStateLoss();
        } else {
            fragment.setArguments(bundle);
            transaction.replace(R.id.frame_container, fragment);
            transaction.commitAllowingStateLoss();
        }
    }

    @Override
    public void initListener() {

        edt_main_search_enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(activity, ActSearch.class));
            }
        });
    }

    @Override
    public void initData() {
        layout_main_activity_toolbar.setVisibility(View.VISIBLE);
        download_layout.setVisibility(View.GONE);
        if (!isGetAdvertisementDialogData) {
            isGetAdvertisementDialogData = true;
            getAdvertisementDialogData();//获取广告弹窗信息
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
    /*
     移植过来
     */
    /**
     * 获取首页弹窗Dialog广告
     */
    public void getAdvertisementDialogData() {
        Log.d(TAG, "getAdvertisementDialogData: " + UrlBll.AdvertisementApi.RECOMMENDED_ADVERTISEMENT);
        APIRequest bannerRequest = APIRequestInstance.getReqUrl(TAG, UrlBll.AdvertisementApi.RECOMMENDED_ADVERTISEMENT, null, new ResponseNetworkTask() {

            public void onSuccess(ApiResponseOuterClass.ApiResponse apiResponse) {
                try {
                    showAdvertisementDialog(apiResponse);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(int code, String msg) {
                Log.d("FLY", "code: " + code + "\nmsg: " + msg);
            }
        }, null);
        KFZSNetwork.addRequest(bannerRequest);
    }

    private void showAdvertisementDialog(ApiResponseOuterClass.ApiResponse apiResponse) {
        if (apiResponse == null || apiResponse.getRecommendedGamesList().isEmpty()) {
            Log.d(TAG, "The showAdvertisementDialog response is null ");
            return;
        }

        final RecommendedGameOuterClass.RecommendedGame recommendeGame = apiResponse.getRecommendedGamesList().get(0);
        final String splashImageUrL = recommendeGame.getImageUrl();
        Log.d(TAG, "splashImageUrL: " + splashImageUrL);
        final String splashImageUr1 = recommendeGame.getTitle();
        Log.d(TAG, "splashImageUrL: " + splashImageUr1);
        final GameOuterClass.Game game = recommendeGame.getGame();
        Log.d(TAG, "game: " + game.toString());
        if (!TextUtils.isEmpty(splashImageUrL)) {
            if (gameDialog != null) {
                gameDialog.dismiss();
            }
            gameDialog = new AppHomepageAdvertisementDialog(activity);
            gameDialog.setShutImg(BitmapFactory.decodeResource(getResources(), R.drawable.btn_dialog_close));
            gameDialog.setBackground(splashImageUrL);
            if (getBtntext(recommendeGame).equals(getString(R.string.book_now))) {
                gameDialog.setCanceledOnTouchOutside(true);
                gameDialog.setCanceledOnTouchOutside(true);
                gameDialog.setCancelable(true);
                gameDialog.setDownloadOnOnclickListener(getBtntext(recommendeGame), new AppHomepageAdvertisementDialog.onDownloadOnclickListener() {
                    @Override
                    public void onDownloadClick() {
                        SkipUtils.getInstance().goGameDetails(activity,
                                recommendeGame.getGame().getId());
                    }
                });
                gameDialog.setBackgroundOnclickListener(new AppHomepageAdvertisementDialog.onBackOnclickListener() {
                    @Override
                    public void onClick() {
                        SkipUtils.getInstance().goGameDetails(activity, recommendeGame.getGame().getId());
                    }
                });


            } else {
                gameDialog.setDownloadOnOnclickListener(getBtntext(recommendeGame),
                        new AppHomepageAdvertisementDialog.onDownloadOnclickListener() {
                            @Override
                            public void onDownloadClick() {
                                final String downloadUrl = game.getDownloadUrl();
                                if (!TextUtils.isEmpty(downloadUrl) && !downloadUrl.endsWith(".apk")) {
                                    String url = UrlBll.GameApi.DOWNLOAD_REDIRECT + "game_id=" + game.getId() + "&channel=" + DataSave.getInstance().getChannelName();
                                    OkHttpUtils.get().url(url).build().execute(new StringCallback() {
                                        @Override
                                        public void onError(Call call, Exception e, int id) {
                                        }

                                        @Override
                                        public void onResponse(String response, int id) {
                                            if (!TextUtils.isEmpty(response)) {
                                                try {
                                                    JSONObject object = new JSONObject(response);
                                                    String realUrl = object.optString("DownloadUrl");
                                                    if (TextUtils.isEmpty(realUrl))
                                                        Toast.makeText(activity, "获取" + DataSave.getInstance().getChannelName() + "渠道下载地址失败", Toast.LENGTH_SHORT).show();
                                                    else {
                                                        KFZSApp.getInstance().mRealDownloadUrl.put(realUrl, downloadUrl);
                                                        DownLoadInfo downloadInfo = addNewDownloadTask(game.getGameName(), realUrl, game.getPackageName(),
                                                                Integer.parseInt(game.getVersionCode()), game.getIconImage(), game.getSize(), game.getId(), STATUS_ING);
                                                        mDownloadTaskService.start(downloadInfo);
                                                        EventBus.getDefault().post(BigEvent.get()
                                                                .setEventTypes(EventTypes.TIPS_DOWN_ICON));
                                                    }
                                                } catch (JSONException e) {
                                                    e.printStackTrace();
                                                }
                                            }

                                        }
                                    });
                                } else {
                                    DownLoadInfo downloadInfo = addNewDownloadTask(game.getGameName(),
                                            downloadUrl,
                                            game.getPackageName(),
                                            Integer.parseInt(game.getVersionCode()),
                                            game.getIconImage(),
                                            game.getSize(),
                                            game.getId(),
                                            STATUS_ING);

                                    mDownloadTaskService.start(downloadInfo);
                                    EventBus.getDefault().post(BigEvent.get()
                                            .setEventTypes(EventTypes.TIPS_DOWN_ICON));
                                }
                            }
                        });

                gameDialog.setBackgroundOnclickListener(new AppHomepageAdvertisementDialog.onBackOnclickListener() {
                    @Override
                    public void onClick() {
                        Intent intent = new Intent(activity, ActGameDetails.class);
                        intent.putExtra(KFIntentKeys.EXTRA_GAME_ID, recommendeGame.getGameId() + "");
                        activity.startActivity(intent);
                    }
                });
            }


            gameDialog.show();
        } else {
            Log.d(TAG, "showAdvertisementDialog: game or splashImageUrL is null");
        }
    }

    private DownLoadInfo addNewDownloadTask(String gameName, String downloadUrl, String packageName,
                                            int versionCode, String iconUrl, String size, Integer gameId, int state) {

        final DownLoadInfo task = new DownLoadInfo();
        task.setMIconUrl(iconUrl);
        task.setMGameName(gameName);
        task.setMDownloadUrl(downloadUrl);
        task.setMPackageName(packageName);
        task.setMVersionCode(versionCode);
        task.setMTotalSize(Double.valueOf(size));
        task.setMGameID(gameId);
        task.setMStatus(state);
        new Thread(new Runnable() {
            @Override
            public void run() {
                mDownloadTaskService.addDownloadTask(task);
            }
        }).start();
        return task;
    }


    /**
     * 返回首页启动广告弹窗的按钮文本
     *
     * @param game
     * @return
     */
    private String getBtntext(RecommendedGameOuterClass.RecommendedGame game) {
        String backStr = "立即下载";
        if (TextUtils.isEmpty(game.getApkUrl())) {
            backStr = getString(R.string.book_now);
        }
        return backStr;
    }
    /**
     * 主要的事件广播接收更新处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(BigEvent event) {
        switch (event.getEventTypes()) {
            case TIPS_DOWN_ICON:
//                mImgDot.setVisibility(View.VISIBLE);
                  TitleBarUtils.getInstance()
                          .setRightRedPoint(activity, View.VISIBLE);
                break;
            case STORAGE_LOW:
                DialogStorageLow.showDialog(this);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
