package com.itant.shiwushu.ui.menu.me;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.signature.ObjectKey;
import com.itant.shiwushu.MainActivity;
import com.itant.shiwushu.R;
import com.itant.shiwushu.base.BaseSkinFragment;
import com.itant.shiwushu.bean.LostFound;
import com.itant.shiwushu.bean.User;
import com.itant.shiwushu.listener.OnUserUpdateListener;
import com.itant.shiwushu.manager.ExecutorManager;
import com.itant.shiwushu.manager.ThemeManager;
import com.itant.shiwushu.manager.ToastManager;
import com.itant.shiwushu.manager.UserManager;
import com.itant.shiwushu.tool.ActivityTool;
import com.itant.shiwushu.tool.DialogTool;
import com.itant.shiwushu.tool.ThemeTool;
import com.itant.shiwushu.tool.file.FileTool;
import com.itant.shiwushu.ui.list.PostListActivity;
import com.itant.shiwushu.ui.menu.me.info.UserInfoActivity;

import java.io.File;

import cn.feng.skin.manager.loader.SkinManager;
import de.hdodenhof.circleimageview.CircleImageView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Jason on 2018/10/2.
 */

public class MeFragment extends BaseSkinFragment implements View.OnClickListener, OnUserUpdateListener {
    private User user;
    private CircleImageView iv_head;
    private TextView tv_nickname;
    private TextView tv_saying;
    private TextView tv_vip_flag;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_me;
    }

    @Override
    public void initViews(View view) {
        //带白色边框的圆形图片加载
        view.findViewById(R.id.ll_about).setOnClickListener(this);
        view.findViewById(R.id.ll_theme).setOnClickListener(this);
        view.findViewById(R.id.ll_exit).setOnClickListener(this);
        view.findViewById(R.id.ll_feedback).setOnClickListener(this);
        view.findViewById(R.id.ll_setting).setOnClickListener(this);
        view.findViewById(R.id.ll_head).setOnClickListener(this);
        view.findViewById(R.id.ll_clean).setOnClickListener(this);
        view.findViewById(R.id.ll_publish).setOnClickListener(this);
        view.findViewById(R.id.ll_favorite).setOnClickListener(this);

        iv_head = view.findViewById(R.id.iv_head);
        tv_nickname = view.findViewById(R.id.tv_nickname);
        tv_saying = view.findViewById(R.id.tv_saying);
        tv_vip_flag = view.findViewById(R.id.tv_vip_flag);
        initUserInfo(false);
        UserManager.getInstance().registerUserUpdateListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        UserManager.getInstance().unRegisterUserUpdateListener(this);
    }

    /**
     * 初始化个人信息
     * @param isFromUpdating 是否来自用户编辑资料后的加载，如果是，则需要忽略缓存
     */
    private void initUserInfo(boolean isFromUpdating) {
        RequestOptions options;
        if (isFromUpdating) {
            // 清除缓存，内存的清除要放在主线程，磁盘放子线程，这样才能正确清除
            Glide.get(activity).clearMemory();
            ExecutorManager.getInstance().getFixedExecutor().submit(new Runnable() {
                @Override
                public void run() {
                    Glide.get(activity).clearDiskCache();
                }
            });

            options = new RequestOptions()
                    .diskCacheStrategy(DiskCacheStrategy.NONE)
                    .skipMemoryCache(true)
                    .signature(new ObjectKey(System.currentTimeMillis()));
        } else {
            options = new RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL);
        }

        user = UserManager.getInstance().getUser();
        if (user == null) {
            return;
        }

        if (!TextUtils.isEmpty(user.getHeadIcon())) {
            Glide.with(this).load(user.getHeadIcon())
                    .apply(options)
                    .into(iv_head);
        }
        tv_nickname.setText(user.getNickName());
        if (user.getUserType() == User.USER_TYPE_VIP) {
            tv_vip_flag.setVisibility(View.VISIBLE);
        } else {
            tv_vip_flag.setVisibility(View.GONE);
        }
        if (!TextUtils.isEmpty(user.getSaying())) {
            tv_saying.setText(user.getSaying());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_favorite:
                // 我的收藏
                Intent favoriteIntent = new Intent(activity, PostListActivity.class);
                favoriteIntent.putExtra(LostFound.KEY_LOST_TYPE, LostFound.LOST_TYPE_FAVORITE);
                ActivityTool.startActivity(activity, favoriteIntent);
                break;
            case R.id.ll_publish:
                // 我的发布
                Intent publishIntent = new Intent(activity, PostListActivity.class);
                publishIntent.putExtra(LostFound.KEY_LOST_TYPE, LostFound.LOST_TYPE_PUBLISH);
                ActivityTool.startActivity(activity, publishIntent);
                break;

            case R.id.ll_about:
                // 关于我们
                ActivityTool.startActivity(activity, AboutActivity.class);
                break;

            case R.id.ll_theme:
                // 换肤
                int mode = ThemeManager.getInstance().getInt(ThemeManager.KEY_THEME_MODE, ThemeManager.THEME_MODE_DEFAULT);
                if (mode == ThemeManager.THEME_MODE_DEFAULT) {
                    ThemeManager.getInstance().putInt(ThemeManager.KEY_THEME_MODE, ThemeManager.THEME_MODE_RED);
                    String SKIN_NAME = "red.skin";
                    String SKIN_DIR = FileTool.getSkinPath(activity, SKIN_NAME);
                    File skin = new File(SKIN_DIR);
                    SkinManager.getInstance().load(skin.getAbsolutePath(), null);
                } else if (mode == ThemeManager.THEME_MODE_RED) {
                    ThemeManager.getInstance().putInt(ThemeManager.KEY_THEME_MODE, ThemeManager.THEME_MODE_BLUE);
                    String SKIN_NAME = "blue.skin";
                    String SKIN_DIR = FileTool.getSkinPath(activity, SKIN_NAME);
                    File skin = new File(SKIN_DIR);
                    SkinManager.getInstance().load(skin.getAbsolutePath(), null);
                } else {
                    ThemeManager.getInstance().putInt(ThemeManager.KEY_THEME_MODE, ThemeManager.THEME_MODE_DEFAULT);
                    SkinManager.getInstance().restoreDefaultTheme();
                }

                // 直接设置状态栏颜色，就不用重启Activity了，但是会有兼容性问题，比如BottomNavigationView在5.0以下无法立即更改颜色
                ThemeTool.changeStatusColor(activity, mode);

                //recreate() + getTheme()实现改变主题（状态栏）
                //activity.recreate();
                break;

            case R.id.ll_feedback:
                DialogTool.showFeedbackDialog(activity, "", "", "", "");
                break;

            case R.id.ll_head:
            case R.id.ll_setting:
                // 编辑资料
                ActivityTool.startActivity(activity, UserInfoActivity.class);
                break;

            case R.id.ll_clean:
                ((MainActivity)activity).setLoading(true);
                Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() {
                    @Override
                    //将事件发射出去,持有观察者的对象
                    public void subscribe(ObservableEmitter<String> e) throws Exception {
                        // 清理缓存
                        File publishDir = FileTool.getPublishDir(activity);
                        if (publishDir.exists()) {
                            File[] files = publishDir.listFiles();
                            if (files != null && files.length > 0) {
                                for (File file : files) {
                                    file.delete();
                                }
                            }
                        }
                        e.onNext("compress completed");
                        e.onComplete();
                    }
                });

                observable.observeOn(AndroidSchedulers.mainThread())
                        .subscribeOn(Schedulers.io())
                        .subscribe(new Observer<String>() {
                            @Override
                            public void onSubscribe(Disposable d) {

                            }

                            @Override
                            public void onNext(String beans) {
                                ((MainActivity)activity).setLoading(false);
                                ToastManager.getInstance().toastShort("清理成功");
                            }

                            @Override
                            public void onError(Throwable e) {
                                ((MainActivity)activity).setLoading(false);
                            }

                            @Override
                            public void onComplete() {
                                ((MainActivity)activity).setLoading(false);
                            }
                        });

                break;

            case R.id.ll_exit:
                // 退出
                DialogTool.showExitDialog(activity);
                break;
        }
    }

    @Override
    public void onUserDataUpdate(User user) {
        // 用户数据更新了
        if (user != null) {
            UserManager.getInstance().setUser(user);
            initUserInfo(true);
        }
    }
}
