package com.kfzs.duanduan.datashare;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

import com.kfzs.duanduan.data.graph.provider.channel.Channel;
import com.kfzs.duanduan.data.graph.provider.channel.ChannelDao;
import com.kfzs.duanduan.data.graph.provider.channel.DaoMaster;
import com.kfzs.duanduan.data.graph.provider.channel.DaoSession;
import com.kfzs.duanduan.data.graph.provider.current.Current;
import com.kfzs.duanduan.data.graph.provider.current.CurrentDao;
import com.kfzs.duanduan.data.graph.provider.player.User;
import com.kfzs.duanduan.data.graph.provider.player.UserDao;
import com.kfzs.duanduan.data.graph.provider.user.UserBean;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfo;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfoDao;

import java.util.List;

/**
 * 端端privoder工具
 *
 * @author kemllor
 * @date 2017/6/15   15:27
 **/

public class DDProviderHelper {

    private static DDProviderHelper mInstance;

    public static synchronized DDProviderHelper getInstance() {
        if (mInstance == null) {
            mInstance = new DDProviderHelper();
        }
        return mInstance;
    }

    private DDProviderHelper() {
    }

    /**
     * 获取用户列表
     *
     * @param context
     * @return
     */
    public List<User> getUserList(Context context) {
        DaoSession daoSession = getDaossion(context);
        List<User> list = daoSession.getUserDao().queryBuilder().build().list();
        return list;
    }

    /**
     * 删除指定user；
     *
     * @param context
     * @param userID
     * @return
     */
    public List<User> deleteUser(Context context, String userID) {
        DaoSession daoSession = getDaossion(context);
        UserDao userDao = daoSession.getUserDao();
        User user = userDao.queryBuilder().where(UserDao.Properties.MUserId.eq(userID)).build().unique();
        if (user != null) {
            userDao.delete(user);
        }
        List<User> list = userDao.queryBuilder().build().list();
        return list;
    }


    /**
     * 获取指定user；
     *
     * @param context
     * @param userID
     * @return
     */
    public User getUser(Context context, String userID) {
        DaoSession daoSession = getDaossion(context);
        UserDao userDao = daoSession.getUserDao();
        User user = userDao.queryBuilder().where(UserDao.Properties.MUserId.eq(userID)).build().unique();
        return user;
    }


    /**
     * 设置渠道名;
     *
     * @param context
     * @param channel
     */
    public void setChannel(Context context, Channel channel) {
        DaoSession daossion = getDaossion(context);
        ChannelDao channelDao = daossion.getChannelDao();
        Channel currentChannel = channelDao.queryBuilder().build().unique();
        if (currentChannel != null) {
            channelDao.deleteAll();
        }
        channelDao.insert(channel);
    }

    /**
     * 获取渠道名
     *
     * @param context
     * @return
     */
    public Channel getChannel(Context context) {
        Channel channel = getDaossion(context).getChannelDao().queryBuilder().build().unique();
        return channel;
    }

    /**
     * 删除所有user；
     *
     * @param context
     * @return
     */
    public boolean deleteAllUser(Context context) {
        try {
            DaoSession daoSession = getDaossion(context);
            UserDao userDao = daoSession.getUserDao();
            userDao.deleteAll();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 删除currentUser；
     *
     * @param context
     * @return
     */
    public boolean deleteCurrent(Context context) {
        try {
            DaoSession daoSession = getDaossion(context);
            CurrentDao currentDao = daoSession.getCurrentDao();
            currentDao.deleteAll();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 添加或者更新用户；
     *
     * @param context
     * @param user
     */
    public void addOrUpdateUser(Context context, User user) {
        DaoSession daossion = getDaossion(context);
        UserDao userDao = daossion.getUserDao();
        User u = userDao.queryBuilder().where(UserDao.Properties.MUserId.eq(user.getMUserId())).build().unique();
        if (u != null) {
            user.setMId(u.getMId());
            userDao.update(user);
        } else
            userDao.insert(user);
        Current current = new Current(user);
        setLastUser(context, current);
    }


    public void addOrUpdatePlayer(Context context, User user, String gameCode) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(YogConfig.Player.TOKEN, user.getMToken());
        values.put(YogConfig.Player.AVATAR, user.getMAvatar());
        values.put(YogConfig.Player.CARDID, user.getMUserCard());
//        values.put(YogConfig.Player.CHANNEL, user.c());
        values.put(YogConfig.Player.DD_USERID, user.getMUserId());
        values.put(YogConfig.Player.MOBILE, user.getMMobile());
//        values.put(YogConfig.Player.MONEY, user.mo());
//        values.put(YogConfig.Player.CODE, user.());
        values.put(YogConfig.Player.ID, user.getMId());
//        values.put(YogConfig.Player.ISAUTH, user.getMIsBind());
        values.put(YogConfig.Player.ISBIND, user.getMIsBind());
        values.put(YogConfig.Player.USERNAME, user.getMUserName());
//        values.put(YogConfig.Player.USERID, user.ui());
        values.put(YogConfig.Player.OPENID, user.getMOpenId());
        values.put(YogConfig.Player.NICKNAME, user.getMNickName());
        values.put(YogConfig.Player.UPDATETIME, user.getMUpdateTime());
        values.put(YogConfig.Player.USERICON, user.getMUserIcon());


        Uri uri = Uri.parse(YogConfig.uriStr + context.getPackageName() + gameCode + "/PLAYER");
        //TODO 呵呵
        try {
            resolver.insert(uri, values);
        } catch (Exception e) {
            try {
                resolver.update(uri, values, null, null);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }


    /**
     * 设置当前帐号
     *
     * @param context
     * @param user
     */
    public void setLastUser(Context context, Current user) {
        DaoSession daossion = getDaossion(context);
        CurrentDao currentDao = daossion.getCurrentDao();
        currentDao.deleteAll();
        currentDao.insert(user);
    }


    /**
     * 更新当前帐号
     *
     * @param context
     * @param user
     */
    public void updateLastUser(Context context, Current user) {
        DaoSession daossion = getDaossion(context);
        CurrentDao currentDao = daossion.getCurrentDao();
        currentDao.update(user);
    }

    /**
     * 获取当前用户；
     *
     * @param context
     * @return
     */
    public Current getLastUser(Context context) {
        Current current = getDaossion(context).getCurrentDao().queryBuilder().build().unique();
        return current;
    }

    /**
     * 获取当前用户token；
     *
     * @param context
     * @return
     */
    public String getLastUserToken(Context context) {
        Current lastUser = getLastUser(context);
        return lastUser == null ? "" : lastUser.getMToken();
    }


//    public User UserBeantoUser(){
//
//    }


    /**
     * 临时强转User类型，失败返回null
     *
     * @param context
     * @return
     */
    public UserBean getLastUserBean(Context context) {
        Current current = getDaossion(context).getCurrentDao().queryBuilder().build().unique();
        if (current == null) {
            return null;
        }
        UserBean userBean = new UserBean();
        userBean.setNickname(current.getMNickName());
        userBean.setPhone(current.getMMobile());
        userBean.setAvatar(current.getMAvatar());
        userBean.setId(current.getMId());
        userBean.setMail(current.getMEmail());
        userBean.setOpenId(current.getMOpenId());
        userBean.setUid(Integer.valueOf(current.getMUserId()));
        userBean.setUpdateTime(Long.valueOf(current.getMUpdateTime()));
        userBean.setUserIcon(current.getMUserIcon());
        userBean.setUserName(current.getMUserName());
        return userBean;
    }


    /**
     * 获取下载任务列表
     *
     * @param context
     * @return
     */
    public List<DownLoadInfo> getDownloadList(Context context) {
        List<DownLoadInfo> list = getDaossion(context).getDownLoadInfoDao().queryBuilder().build().list();
        return list;
    }


    /**
     * 更新下载任务状态；
     *
     * @param context
     * @param info
     */
    public void updateDownload(Context context, DownLoadInfo info) {
        DownLoadInfoDao loadInfoDao = getDaossion(context).getDownLoadInfoDao();
        loadInfoDao.update(info);
    }

    /**
     * 添加或更新任务
     *
     * @param context
     * @param info
     */
    public boolean addOrUpDataDownloadTask(Context context, DownLoadInfo info) {
        DownLoadInfoDao infoDao = getDaossion(context).getDownLoadInfoDao();
        DownLoadInfo downLoadInfo = infoDao
                .queryBuilder()
                .where(DownLoadInfoDao.Properties.MDownloadUrl.eq(info.getMDownloadUrl()))
                .build()
                .unique();
        try{
            if (downLoadInfo == null) {
                infoDao.insert(info);
                return true;
            } else {
                info.setMId(downLoadInfo.getMId());
                infoDao.update(info);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 删除指定任务；
     *
     * @param context
     * @param gameID
     */
    public List<DownLoadInfo> deleteDownloadTask(Context context, String gameID) {
        DownLoadInfoDao loadInfoDao = getDaossion(context).getDownLoadInfoDao();
        DownLoadInfo loadInfo = loadInfoDao.queryBuilder()
                .where(DownLoadInfoDao.Properties.MGameID.eq(gameID))
                .build()
                .unique();
        loadInfoDao.delete(loadInfo);
        List<DownLoadInfo> loadInfos = loadInfoDao.queryBuilder().build().list();
        return loadInfos;
    }
    /**
     * 删除所有任务；
     *
     * @param context
     */
    public void deleteAllDownloadTask(Context context) {
        DownLoadInfoDao loadInfoDao = getDaossion(context).getDownLoadInfoDao();
        loadInfoDao.deleteAll();
    }


    /**
     * 删除指定任务；
     *
     * @param context
     * @param url
     */
    public boolean deleteDownloadTaskByUrl(Context context, String url) {
        try {
            DownLoadInfoDao loadInfoDao = getDaossion(context).getDownLoadInfoDao();
            DownLoadInfo loadInfo = loadInfoDao.queryBuilder()
                    .where(DownLoadInfoDao.Properties.MDownloadUrl.eq(url))
                    .build()
                    .unique();
            loadInfoDao.delete(loadInfo);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置游戏当前帐号；
     *
     * @param context
     * @param openID
     */
    public void setGameLastPalyer(Context context, String openID, String gameCode) {
        ContentResolver resolver = context.getContentResolver();
        ContentValues values = new ContentValues();
        values.put(YogConfig.Game.LASTUSERID, openID);
        Uri uri = Uri.parse(YogConfig.uriStr + context.getPackageName() + gameCode + "/GAME");
        resolver.update(uri, values, null, null);
    }


    /**
     * 获取游戏当前帐号；
     *
     * @param context
     */
    public Cursor getGameLastPalyer(Context context, String gameCode) {
        ContentResolver resolver = context.getContentResolver();
        Uri uri = Uri.parse(YogConfig.uriStr + context.getPackageName() + gameCode + "/GAME");
        Cursor query = resolver.query(uri, null, null, null, null, null);
        return query;
    }

    /**
     * 插入或更新已授权帐号；
     *
     * @param context
     * @param values
     */
    public void insertOrUpdatePalyer(Context context, ContentValues values, String gameCode) {
        ContentResolver resolver = context.getContentResolver();
        String openId = (String) values.get(YogConfig.Player.OPENID);
        Uri uri = Uri.parse(YogConfig.uriStr + context.getPackageName() + gameCode + "/" + YogConfig.PLAYER + "/" + openId);
        Uri uri2 = Uri.parse(YogConfig.uriStr + context.getPackageName() + gameCode + "/" + YogConfig.PLAYER);
        Cursor query = resolver.query(uri, null, null, null, null);
        if (query == null || query.getCount() == 0) {
            if (query != null)
                query.close();
            resolver.insert(uri2, values);
        } else {
            query.close();
            resolver.update(uri, values, null, null);
        }
    }

    /**
     * 获取游戏用户；
     *
     * @param context
     * @param openId  OpenId
     */
    public Cursor getPlayer(Context context, String openId, String gameCode) {
        ContentResolver resolver = context.getContentResolver();
        Uri uri = Uri.parse(YogConfig.uriStr + context.getPackageName() + gameCode + "/" + YogConfig.PLAYER + "/" + openId);
        return resolver.query(uri, null, null, null, null);
    }


    /**
     * 获取全部玩家帐号信息；
     *
     * @param context
     * @return
     */
    public Cursor getAllPlayer(Context context, String gameCode) {
        ContentResolver resolver = context.getContentResolver();
        Uri uri = Uri.parse(YogConfig.uriStr + context.getPackageName() + gameCode + "/" + YogConfig.PLAYER);
        return resolver.query(uri, null, null, null, null);
    }

    /**
     * 删除指定玩家；
     *
     * @param context
     * @param userId
     */
    public void deletePalyer(Context context, String userId, String gameCode) {
        ContentResolver resolver = context.getContentResolver();
        Uri uri = Uri.parse(YogConfig.uriStr + context.getPackageName() + gameCode + "/" + YogConfig.PLAYER + "/" + userId);
        resolver.delete(uri, null, null);
    }

    private DaoMaster.DevOpenHelper openHelper;

    private synchronized DaoSession getDaossion(Context context) {
        if (openHelper == null) {
            openHelper = new DaoMaster.DevOpenHelper(context, "dd.db");
        }
        return new DaoMaster(openHelper.getReadableDb()).newSession();
    }

    /**
     * 获取下载中的任务；
     *
     * @param ctx
     */
    public List<DownLoadInfo> getDownloadingTask(Context ctx) {
        List<DownLoadInfo> loadInfos = getDaossion(ctx)
                .getDownLoadInfoDao()
                .queryBuilder()
                .where(DownLoadInfoDao.Properties.MStatus.eq(2))
                .build()
                .list();
        return loadInfos;
    }

    /**
     * 获取指定下载任务
     *
     * @param downloadUrl
     */
    public DownLoadInfo getDownloadTask(Context context, String downloadUrl) {
        DownLoadInfo downLoadInfo = getDaossion(context)
                .getDownLoadInfoDao()
                .queryBuilder()
                .where(DownLoadInfoDao.Properties.MDownloadUrl.eq(downloadUrl))
                .build()
                .unique();
        return downLoadInfo;
    }

    /**
     * 获取指定下载任务
     *
     * @param packName
     */
    public DownLoadInfo getDownloadTaskToPackname(Context context, String packName) {
        DownLoadInfo downLoadInfo = getDaossion(context)
                .getDownLoadInfoDao()
                .queryBuilder()
                .where(DownLoadInfoDao.Properties.MPackageName.eq(packName))
                .limit(1)
                .build()
                .unique();
        return downLoadInfo;
    }

    /**
     * 下载任务完成
     *
     * @param ctx
     * @param downloadUrl
     * @param apkPath
     */
    public void setDownloadTaskFinish(Context ctx, String downloadUrl, String apkPath) {
        DownLoadInfo downloadTask = getDownloadTask(ctx, downloadUrl);
        if (downloadTask != null) {
            downloadTask.setMApkPath(apkPath);
            downloadTask.setMStatus(3);//DownloadTaskService.STATUS_FINISH
            getDaossion(ctx).getDownLoadInfoDao().update(downloadTask);
        }
    }

    /**
     * 更新任务状态
     *
     * @param ctx
     * @param percent
     * @param downloadedSize
     * @param totalSize
     * @param downloadTaskId
     * @param downloadUrl
     */
    public void updateDownloadPercent(Context ctx, int percent, double downloadedSize, double totalSize, int downloadTaskId, String downloadUrl, int state) {
        DownLoadInfo downloadTask = getDownloadTask(ctx, downloadUrl);
        if (downloadTask != null) {
            downloadTask.setMPercent(percent);
            downloadTask.setMTotalSize(totalSize);
            downloadTask.setMDownloadedSize(downloadedSize);
            downloadTask.setMDownloadTaskId(downloadTaskId);
            downloadTask.setMStatus(state);//2下载中
            updateDownload(ctx, downloadTask);
        }
    }


    /**
     * 改变任务状态
     *
     * @param ctx
     * @param downloadUrl
     * @param status
     */
    public boolean setDownloadTaskStatus(Context ctx, String downloadUrl, int status) {
        try {
            DownLoadInfo downloadTask = getDownloadTask(ctx, downloadUrl);
            if (downloadTask != null) {
                downloadTask.setMStatus(status);
                updateDownload(ctx, downloadTask);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * app启动  所有任务全部暂停
     *
     * @param context
     */
    public void restoreDownloadTaskStatus(Context context) {
        DownLoadInfoDao downLoadInfoDao = getDaossion(context).getDownLoadInfoDao();
        List<DownLoadInfo> list = downLoadInfoDao
                .queryBuilder()
                .whereOr(DownLoadInfoDao.Properties.MStatus.eq(0), DownLoadInfoDao.Properties.MStatus.eq(2))
                .build()
                .list();

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                DownLoadInfo loadInfo = list.get(i);
                loadInfo.setMStatus(4);
                downLoadInfoDao.update(loadInfo);
            }
        }
    }
}
