package com.android.chmo.ui.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.view.View;
import android.widget.TextView;

import com.android.chmo.R;
import com.android.chmo.app.ChmoApplication;
import com.android.chmo.base.BaseActivity;
import com.android.chmo.http.RequestCallback;
import com.android.chmo.http.service.UserService;
import com.android.chmo.ui.fragment.BrokerFragment;
import com.android.chmo.ui.fragment.FindFragment;
import com.android.chmo.ui.fragment.HomeFragment;
import com.android.chmo.ui.fragment.MeFragment;
import com.android.chmo.ui.fragment.MessageFragment;
import com.android.chmo.ui.fragment.MineFragment;
import com.android.chmo.ui.view.NoSlideViewPager;
import com.blankj.utilcode.util.AppUtils;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

public class MainActivity extends BaseActivity {
    private final int FRAGMENT_HOME    = 0;
    private final int FRAGMENT_BROKER  = 1;
    private final int FRAGMENT_FIND    = 2;
    private final int FRAGMENT_MESSAGE = 3;
    private final int FRAGMENT_ME      = 4;

    @BindView(R.id.pager)
    NoSlideViewPager mPager;

    @BindView(R.id.tab_home)
    View tabHome;

    @BindView(R.id.tab_broker)
    View tabBroker;

    @BindView(R.id.tab_message)
    View tabMessage;

    @BindView(R.id.tab_me)
    View tabMe;

    @BindView(R.id.find)
    View findBtn;

    @BindView(R.id.unread)
    TextView unreadView;

    private View curTab;

    private int     curFragment;
    private boolean checkAgain;

    @Override
    protected int getContentResId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        mPager.setOffscreenPageLimit(5);
        mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
        curTab = tabHome;
        curTab.setSelected(true);

        registerObserver(true);
        checkUpdate();
    }

    @Override
    protected void onResume() {
        super.onResume();
        fillUnreadView();
        if (checkAgain) {
            checkUpdate();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        registerObserver(false);
    }

    @OnClick({R.id.tab_home, R.id.tab_broker, R.id.tab_message, R.id.tab_me, R.id.find})
    public void onTabClick(View v) {
        if (null != curTab) {
            curTab.setSelected(false);
        }
        curTab = v;
        curTab.setSelected(true);
        switch (v.getId()) {
            case R.id.tab_home:
                curFragment = FRAGMENT_HOME;
                break;
            case R.id.tab_broker:
                curFragment = FRAGMENT_BROKER;
                break;
            case R.id.tab_message:
                curFragment = FRAGMENT_MESSAGE;
                break;
            case R.id.tab_me:
                curFragment = FRAGMENT_ME;
                break;
            case R.id.find:
                curFragment = FRAGMENT_FIND;
                break;
            default:
                break;
        }
        mPager.setCurrentItem(curFragment, false);
    }

    private void fillUnreadView() {
        int count = NIMClient.getService(MsgService.class).getTotalUnreadCount();
        if (count == 0) {
            unreadView.setText("0");
            unreadView.setVisibility(View.GONE);
        } else {
            unreadView.setVisibility(View.VISIBLE);
            unreadView.setText(count > 9 ? "9+" : String.valueOf(count));
        }
    }

    private void registerObserver(boolean register) {
        if (register) {
            registerReceiver(msgCountReceiver, new IntentFilter("com.android.chmo.REFRESH_MSG"));
        } else {
            unregisterReceiver(msgCountReceiver);
        }
    }

    private BroadcastReceiver msgCountReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            fillUnreadView();
        }
    };

    private class MyPagerAdapter extends FragmentPagerAdapter {

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case FRAGMENT_HOME:
                    return Fragment.instantiate(getApplicationContext(), HomeFragment.class.getName());
                case FRAGMENT_BROKER:
                    return Fragment.instantiate(getApplicationContext(), BrokerFragment.class.getName());
                case FRAGMENT_FIND:
                    return Fragment.instantiate(getApplicationContext(), FindFragment.class.getName());
                case FRAGMENT_MESSAGE:
                    return Fragment.instantiate(getApplicationContext(), MessageFragment.class.getName());
                case FRAGMENT_ME:
//                    return Fragment.instantiate(getApplicationContext(), MeFragment.class.getName());
                    return Fragment.instantiate(getApplicationContext(), MineFragment.class.getName());
            }

            throw new RuntimeException("undefine position:" + position);
        }

        @Override
        public int getCount() {
            return 5;
        }
    }


    private long backPressTime = 0;

    @Override
    public void onBackPressed() {
        long time = System.currentTimeMillis();
        if ((time - backPressTime) > 2000) {
            backPressTime = time;
            showToast("再按一次退出应用");
            return;
        }

        super.onBackPressed();
    }

    private void checkUpdate() {
        UserService.checkUpdate(new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject obj = new JSONObject(result);
                    JSONObject android = obj.getJSONObject("data").getJSONObject("android");
                    String currentVersion = getVersion();
                    String latestVersion = android.getString("version");
                    boolean force = android.getBoolean("force");
                    String url = android.getString("url");
                    if (convertVersion(currentVersion) < convertVersion(latestVersion)) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                                .setTitle("提示").setMessage("发现新版本" + latestVersion).setPositiveButton("立即更新", (dialog, which) -> {
                                    dialog.dismiss();
                                    downloadUpdate(url);
                                });
                        if (!force) {
                            builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
                        }
                        builder.setCancelable(false).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String error) {

            }
        });
    }

    private void downloadUpdate(String url) {
        final File file = new File(getExternalCacheDir(), "update.apk");
        final ProgressDialog progressDialog = new ProgressDialog(this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下载");
        progressDialog.setProgress(0);
        progressDialog.setCancelable(false);
        FileDownloader.getImpl().create(url)
                .setPath(file.getPath())
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                        progressDialog.show();
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        progressDialog.setProgress(soFarBytes * 100 / totalBytes);
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        AppUtils.installApp(file, "com.android.chmo.fileProvider");
                        progressDialog.dismiss();
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        progressDialog.dismiss();
                        new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT)
                                .setPositiveButton("重试", (dialog, which) -> downloadUpdate(url))
                                .setTitle("下载失败")
                                .setCancelable(false)
                                .show();
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                }).start();
    }

    public String getVersion() {
        PackageManager manager = this.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            return info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    private int convertVersion(String version) {
        try {
            return Integer.valueOf(version.replace(".", ""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
}
