package com.itant.shiwushu.manager;

import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.itant.shiwushu.bean.User;
import com.itant.shiwushu.constant.ServerHost;
import com.itant.shiwushu.listener.OnUserUpdateListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jason on 2018/8/31.
 */

public class UserManager {

    private static UserManager manager;
    private User user;
    private List<OnUserUpdateListener> userUpdateListenerList;

    private UserManager() {
        String userJson = SharedPreferenceManager.getInstance().getString(SharedPreferenceManager.KEY_USER, "");
        if (!TextUtils.isEmpty(userJson)) {
            user = JSON.parseObject(userJson, User.class);
        }
        userUpdateListenerList = new ArrayList<>();
    }

    public static UserManager getInstance() {
        if (manager == null) {
            init();
        }
        return manager;
    }

    private static synchronized void init() {
        if (manager == null) {
            manager = new UserManager();
        }
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        if (user != null) {
            String headIconUrl = user.getHeadIcon();
            if (!TextUtils.isEmpty(headIconUrl)) {
                if (!headIconUrl.startsWith("http")) {
                    headIconUrl = ServerHost.URL_BASE + headIconUrl;
                    user.setHeadIcon(headIconUrl);
                }
            }
            SharedPreferenceManager.getInstance().putString(SharedPreferenceManager.KEY_USER, JSON.toJSONString(user));
        }
        this.user = user;
    }

    public void registerUserUpdateListener(OnUserUpdateListener listener) {
        if (userUpdateListenerList != null) {
            userUpdateListenerList.add(listener);
        }
    }

    public void unRegisterUserUpdateListener(OnUserUpdateListener listener) {
        if (userUpdateListenerList != null) {
            userUpdateListenerList.remove(listener);
        }
    }

    public void notifyUserDataUpdate(User user) {
        if (userUpdateListenerList != null) {
            for (OnUserUpdateListener listener : userUpdateListenerList) {
                listener.onUserDataUpdate(user);
            }
        }
    }
}
