package com.kfzs.duanduan.data.graph;

import android.content.ContentResolver;
import android.content.Context;

import com.kfzs.duanduan.data.graph.provider.KFZSGraphProvider;
import com.kfzs.duanduan.data.graph.provider.user.UserBean;
import com.kfzs.duanduan.data.graph.provider.user.UserContentValues;
import com.kfzs.duanduan.data.graph.provider.user.UserCursor;
import com.kfzs.duanduan.data.graph.provider.user.UserSelection;

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

/**
 * <pre>
 *     sinlov
 *
 *     /\__/\
 *    /`    '\
 *  ≈≈≈ 0  0 ≈≈≈ Hello world!
 *    \  --  /
 *   /        \
 *  /          \
 * |            |
 *  \  ||  ||  /
 *   \_oo__oo_/≡≡≡≡≡≡≡≡o
 *
 * </pre>
 * Created by sinlov on 17/3/10.
 */
public class KFZSUserHelper {

    public static final int SUCCESS = 1;
    public static final int NOT_HAS_ANY_USER = 2 ^ 1;
    public static final int HEAD_USER_HAS_CHANGE_STOP_JOB = 3 ^ 1;
    public static final int CAN_NOT_FIND_USER_QUERY_OUT_BY_KEY = 4 ^ 1;

    private static KFZSUserHelper instance;
    private UserBean headUserBean;

    public boolean isHasHeadUserInfo(Context ctx) {
        UserSelection userSelection = new UserSelection();
        int count = userSelection.count(ctx);
        return count > 0;
    }

    public UserBean findOutHeadUser(Context ctx) {
        UserSelection where = new UserSelection();
        int count = where.count(ctx);
        if (count > 0) {
            ContentResolver contentResolver = ctx.getContentResolver();
            where.orderByUpdateTime();
            UserCursor query = where.query(contentResolver);
            if (query == null) {
                throwGraphProviderConfigError();
            }
            int queryCount = query.getCount();
            for (int i = 0; i < queryCount; i++) {
                query.moveToNext();
            }
            UserBean userBean = new UserBean();
            userBean.setUid(query.getUid());
            userBean.setUserName(query.getUserName());
            userBean.setUpdateTime(query.getUpdateTime());
            userBean.setPhone(query.getPhone());
            userBean.setNickname(query.getNickname());
            userBean.setUserIcon(query.getUserIcon());
            userBean.setAvatar(query.getAvatar());
            userBean.setOpenId(query.getOpenId());
            userBean.setMail(query.getMail());
            userBean.setRefreshToken(query.getRefreshToken());
            this.headUserBean = userBean;
            query.close();
            return userBean;
        } else {
            return null;
        }
    }

    public int changeHeadUser(Context ctx, String userName) {
        UserSelection where = new UserSelection();
        int count = where.count(ctx);
        if (count > 0) {
            where.userName(userName);
            ContentResolver contentResolver = ctx.getContentResolver();
            UserCursor query = where.query(contentResolver);
            if (query == null) {
                throwGraphProviderConfigError();
            }
            if (query.getCount() == 0) {
                query.close();
                return NOT_HAS_ANY_USER;
            } else {
                query.moveToNext();
                UserContentValues userContentValues = new UserContentValues();
                userContentValues.putUid(query.getUid());
                userContentValues.putUserName(query.getUserName());
                long nowTime = System.currentTimeMillis();
                userContentValues.putUpdateTime(nowTime);
                userContentValues.putPhone(query.getPhone());
                userContentValues.putNickname(query.getNickname());
                userContentValues.putUserIcon(query.getUserIcon());
                userContentValues.putAvatar(query.getAvatar());
                userContentValues.putOpenId(query.getOpenId());
                userContentValues.putMail(query.getMail());
                userContentValues.putRefreshToken(query.getRefreshToken());
                contentResolver.update(userContentValues.uri(), userContentValues.values(), null, null);
                query.close();
                return SUCCESS;
            }
        } else {
            return CAN_NOT_FIND_USER_QUERY_OUT_BY_KEY;
        }
    }

    public int removeHeadUser(Context ctx) {
        if (this.headUserBean == null) {
            return HEAD_USER_HAS_CHANGE_STOP_JOB;
        }
        String userName = headUserBean.getUserName();
        UserSelection where = new UserSelection();
        ContentResolver contentResolver = ctx.getContentResolver();
        where.userName(userName);
        int delete = where.delete(contentResolver);
        if (delete == 1) {
            findOutHeadUser(ctx);
            return SUCCESS;
        } else {
            return CAN_NOT_FIND_USER_QUERY_OUT_BY_KEY;
        }
    }

    public void insertOrUpdateHeadUser(Context ctx, UserBean userBean) {
        String userName = userBean.getUserName();
        UserContentValues userContentValues = new UserContentValues();
        userContentValues.putUid(userBean.getUid());
        userContentValues.putUserName(userName);
        long nowTime = System.currentTimeMillis();
        userContentValues.putUpdateTime(nowTime);
        userContentValues.putPhone(userBean.getPhone());
        userContentValues.putNickname(userBean.getNickname());
        userContentValues.putUserIcon(userBean.getUserIcon());
        userContentValues.putAvatar(userBean.getAvatar());
        userContentValues.putOpenId(userBean.getOpenId());
        userContentValues.putMail(userBean.getMail());
        userContentValues.putRefreshToken(userBean.getRefreshToken());
        UserSelection where = new UserSelection();
        where.userName(userName);
        ContentResolver contentResolver = ctx.getContentResolver();
        UserCursor query = where.query(contentResolver);
        if (query == null) {
            throwGraphProviderConfigError();
        }
        query.moveToNext();
        if (query.getCount() > -1) {
            contentResolver.insert(userContentValues.uri(), userContentValues.values());
            this.headUserBean = userBean;
        }
        query.close();
    }


    public List<UserBean> checkOutFullUser(Context ctx) {
        ContentResolver contentResolver = ctx.getContentResolver();
        UserSelection userSelection = new UserSelection();
        userSelection.orderByUpdateTime(true);
        UserCursor query = userSelection.query(contentResolver);
        if (query == null) {
            throwGraphProviderConfigError();
        }
        List<UserBean> outList = new ArrayList<UserBean>();
        while (query.moveToNext()) {
            UserBean userBean = new UserBean();
            userBean.setUid(query.getUid());
            userBean.setUserName(query.getUserName());
            userBean.setUpdateTime(query.getUpdateTime());
            userBean.setPhone(query.getPhone());
            userBean.setNickname(query.getNickname());
            userBean.setUserIcon(query.getUserIcon());
            userBean.setAvatar(query.getAvatar());
            userBean.setOpenId(query.getOpenId());
            userBean.setMail(query.getMail());
            userBean.setRefreshToken(query.getRefreshToken());
            outList.add(userBean);
        }
        query.close();
        return outList;
    }

    private void throwGraphProviderConfigError() {
        throw new IllegalArgumentException("Please check config!\nNow com.kfzs.duanduan.data.graph.provider.KFZSGraphProvider AUTHORITY is set: " + KFZSGraphProvider.AUTHORITY + " maybe error!");
    }

    /**
     * remove all user and return delete session count
     *
     * @param ctx {@link Context}
     * @return count of delete session raw
     */
    public int clearAllUser(Context ctx) {
        UserSelection userSelection = new UserSelection();
        int count = userSelection.count(ctx);
        if (count > 0) {
            this.headUserBean = null;
            return userSelection.delete(ctx);
        } else {
            return 0;
        }
    }

    public static KFZSUserHelper getInstance() {
        if (instance == null) {
            instance = new KFZSUserHelper();
        }
        return instance;
    }

    private KFZSUserHelper() {
    }
}
