package com.android.chmo.utils;

import com.android.chmo.app.ChmoApplication;
import com.android.chmo.db.CommDbHelper;
import com.android.chmo.http.RequestCallback;
import com.android.chmo.http.response.LoginRes;
import com.android.chmo.http.service.UserService;
import com.android.chmo.model.LoginUser;
import com.google.gson.Gson;

import org.xutils.ex.DbException;

import java.util.List;

/**
 * Created by Administrator on 2018/8/2.
 */

public class LoginUtils {


    public static void saveLoginUser(LoginUser user) {
        clearLoginUser();
        CommDbHelper.get().saveOrUpdate(user);
        ChmoApplication.getApp().setLoginUser(user);
    }

    /**
     * 查询登录信息
     * @return
     */
    public static LoginUser getLoginUser() {
        LoginUser user = null;
        try {
            List<LoginUser> list =  CommDbHelper.get().getDbManager().findAll(LoginUser.class);
            if (null != list && !list.isEmpty()) {
                user = list.get(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 清除登录信息
     */
    public static void clearLoginUser() {
        try {
            CommDbHelper.get().getDbManager().delete(LoginUser.class);
            ChmoApplication.getApp().setLoginUser(null);
        }catch (DbException e) {
            e.printStackTrace();
        }
    }

    public static void refreshUser() {
        UserService.getUser(new RequestCallback() {
            @Override
            public void onSuccess(String result) {
                LoginRes res = new Gson().fromJson(result, LoginRes.class);
                if(res.data != null) {
                    LoginUser user = new LoginUser();
                    user.setUser(res.data);
                    LoginUtils.saveLoginUser(user);
                }
            }

            @Override
            public void onFailure(String error) {
            }
        });
    }


}
