package in.techware.carrefour.dbUtils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;

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

/*
import in.techware.afcetcbus.database.entity.LocationEntity;
import in.techware.carrefour.app.App;
import in.techware.carrefour.dbUtils.dao.ContactDao;
import in.techware.carrefour.dbUtils.dao.EventDao;
import in.techware.carrefour.dbUtils.dao.LocationDao;
import in.techware.carrefour.dbUtils.dao.PollDao;
import in.techware.carrefour.dbUtils.entity.ContactEntity;
import in.techware.carrefour.dbUtils.entity.EventEntity;
import in.techware.carrefour.dbUtils.entity.PollEntity;
import in.techware.carrefour.model.ChatBean;
import in.techware.carrefour.model.ChatListBean;
import in.techware.carrefour.model.PaginationBean;
import in.techware.carrefour.util.AppConstants;
*/

/**
 * Created by Jemsheer K D on 13 February, 2018.
 * Package in.techware.carrefour.dbUtils
 * Project Carrefour
 */
public class DBHandler extends SQLiteOpenHelper {
    // All Static variables


    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "carrefour_chat";


    /* chat_list Table Coloumn names */
    private static final String KEY_CHAT_ID = "chatID";
    private static final String KEY_CHAT_ORIGINAL_ID = "originalID";
    private static final String KEY_CHAT_TYPE = "type";
    private static final String KEY_CHAT_MESSAGE = "message";
    private static final String KEY_CHAT_IMAGE_URL = "image_url";
    private static final String KEY_CHAT_VIDEO_URL = "video_url";
    private static final String KEY_CHAT_VIDEO_DURATION = "video_duration";
    private static final String KEY_CHAT_SNAPSHOT_URL = "snapshot_url";
    private static final String KEY_CHAT_STICKER_URL = "sticker_url";
    private static final String KEY_CHAT_AUDIO_URL = "audio_url";
    private static final String KEY_CHAT_DOCUMENT_URL = "document_url";
    private static final String KEY_CHAT_RECEIVER_ID = "receiver_id";
    private static final String KEY_CHAT_SENDER_ID = "sender_id";
    private static final String KEY_CHAT_SENDER_NAME = "sender_name";
    private static final String KEY_CHAT_RECEIVER_NAME = "receiver_name";
    private static final String KEY_CHAT_SENDER_PHOTO = "sender_photo";
    private static final String KEY_CHAT_RECEIVER_PHOTO = "receiver_photo";
    private static final String KEY_CHAT_TIMESTAMP = "time";
    private static final String KEY_CHAT_TREE_TYPE = "tree_type";
    private static final String KEY_CHAT_IS_TREE_CHAT = "is_tree_chat";
    private static final String KEY_CHAT_IS_GROUP_CHAT = "is_group_chat";
    private static final String KEY_CHAT_IS_CORPORATE_TREE = "is_corporate_tree";
    private static final String KEY_CHAT_IS_MINISTRY_TREE = "is_ministry_tree";
    private static final String KEY_CHAT_GROUP_ID = "group_id";
    private static final String KEY_CHAT_EVENT_ID = "event_id";
    private static final String KEY_CHAT_POLL_ID = "poll_id";
    private static final String KEY_CHAT_LOCATION_ID = "location_id";
    private static final String KEY_CHAT_CONTACT_ID = "contact_id";
    private static final String KEY_CHAT_IS_READ = "is_read";
    private static final String KEY_CHAT_IS_SENT = "is_sent";

    // chatBeans table name
    private static final String PREFIX_TABLE_NAME_PRIVATE_CHAT = "private_chat_";
    private static final String PREFIX_TABLE_NAME_GROUP_CHAT = "group_chat_";
    private static final String PREFIX_CREATE_TABLE_IF_NOT_EXISTS = "CREATE TABLE IF NOT EXISTS ";
    private static final String SUFFIX_CREATE_CHAT_LIST_TABLE = "("
            + KEY_CHAT_ID + " TEXT PRIMARY KEY,"
            + KEY_CHAT_ORIGINAL_ID + " TEXT,"
            + KEY_CHAT_TYPE + " INTEGER,"
            + KEY_CHAT_MESSAGE + " TEXT,"
            + KEY_CHAT_IMAGE_URL + " TEXT,"
            + KEY_CHAT_VIDEO_URL + " TEXT,"
            + KEY_CHAT_VIDEO_DURATION + " TEXT,"
            + KEY_CHAT_SNAPSHOT_URL + " TEXT,"
            + KEY_CHAT_STICKER_URL + " TEXT,"
            + KEY_CHAT_AUDIO_URL + " TEXT,"
            + KEY_CHAT_DOCUMENT_URL + " TEXT,"
            + KEY_CHAT_GROUP_ID + " TEXT,"
            + KEY_CHAT_EVENT_ID + " TEXT,"
            + KEY_CHAT_POLL_ID + " TEXT,"
            + KEY_CHAT_LOCATION_ID + " TEXT,"
            + KEY_CHAT_CONTACT_ID + " TEXT,"
            + KEY_CHAT_RECEIVER_ID + " TEXT,"
            + KEY_CHAT_RECEIVER_NAME + " TEXT,"
            + KEY_CHAT_RECEIVER_PHOTO + " TEXT,"
            + KEY_CHAT_SENDER_ID + " TEXT,"
            + KEY_CHAT_SENDER_NAME + " TEXT,"
            + KEY_CHAT_SENDER_PHOTO + " TEXT,"
            + KEY_CHAT_TREE_TYPE + " INTEGER,"
            + KEY_CHAT_TIMESTAMP + " INTEGER,"
            + KEY_CHAT_IS_CORPORATE_TREE + " INTEGER DEFAULT 0,"
            + KEY_CHAT_IS_MINISTRY_TREE + " INTEGER DEFAULT 0,"
            + KEY_CHAT_IS_GROUP_CHAT + " INTEGER DEFAULT 0,"
            + KEY_CHAT_IS_TREE_CHAT + " INTEGER DEFAULT 0,"
            + KEY_CHAT_IS_READ + " INTEGER DEFAULT 0,"
            + KEY_CHAT_IS_SENT + " INTEGER DEFAULT 0"
            + ")";



    public DBHandler(Context context) {
        //super(context);
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
//        db.execSQL(CREATE_INNER_CIRCLE_CHAT_TABLE);

    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
//        db.execSQL("DROP TABLE IF EXISTS " + TABLE_INNER_CIRCLE_CHAT);
        // Create tables again
        onCreate(db);
    }

/*

    *//*CHAT TABLES AND MANIPULATIONS*//*

    // Adding new Chat
    public boolean addChat(String tableName, ChatBean bean, boolean isGroupChat) {
        checkDataBaseForTable(tableName, isGroupChat);
        String tableNamePrefix = getTableNamePrefix(isGroupChat);
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_CHAT_ID, bean.getId());
        values.put(KEY_CHAT_ORIGINAL_ID, bean.getOriginalID());
        values.put(KEY_CHAT_TYPE, bean.getType());
        values.put(KEY_CHAT_MESSAGE, bean.getMessage());
        values.put(KEY_CHAT_IMAGE_URL, bean.getImageURL());
        values.put(KEY_CHAT_VIDEO_URL, bean.getVideoURL());
        values.put(KEY_CHAT_VIDEO_DURATION, bean.getVideoDuration());
        values.put(KEY_CHAT_SNAPSHOT_URL, bean.getSnapshotURL());
        values.put(KEY_CHAT_STICKER_URL, bean.getStickerURL());
        values.put(KEY_CHAT_AUDIO_URL, bean.getAudioURL());
        values.put(KEY_CHAT_DOCUMENT_URL, bean.getDocumentURL());
        values.put(KEY_CHAT_RECEIVER_ID, bean.getReceiverID());
        values.put(KEY_CHAT_SENDER_ID, bean.getSenderID());
        values.put(KEY_CHAT_SENDER_NAME, bean.getSenderName());
        values.put(KEY_CHAT_RECEIVER_NAME, bean.getReceiverName());
        values.put(KEY_CHAT_SENDER_PHOTO, bean.getSenderPhoto());
        values.put(KEY_CHAT_RECEIVER_PHOTO, bean.getReceiverPhoto());
        values.put(KEY_CHAT_TIMESTAMP, bean.getTimestamp());
        values.put(KEY_CHAT_TREE_TYPE, bean.getTreeType());
        values.put(KEY_CHAT_IS_TREE_CHAT, bean.isGroupChat());
        values.put(KEY_CHAT_IS_GROUP_CHAT, bean.isGroupChat());
        values.put(KEY_CHAT_IS_CORPORATE_TREE, bean.isCorporateTree());
        values.put(KEY_CHAT_IS_MINISTRY_TREE, bean.isMinistryTree());
        values.put(KEY_CHAT_GROUP_ID, bean.getGroupID());
        values.put(KEY_CHAT_EVENT_ID, bean.getEventID());
        values.put(KEY_CHAT_POLL_ID, bean.getPollID());
        values.put(KEY_CHAT_LOCATION_ID, bean.getLocationID());
        values.put(KEY_CHAT_CONTACT_ID, bean.getContactID());
        values.put(KEY_CHAT_IS_READ, bean.isRead());
        values.put(KEY_CHAT_IS_SENT, bean.isSent());

        if (bean.getType() == AppConstants.CHAT_TYPE_LOCATION) {
            LocationEntity locationEntity = new LocationEntity(bean.getLocationBean());
            locationDao = CarrefourRoomDatabase.getDatabase(App.getInstance()).locationDao();
            locationDao.insert(locationEntity);
        }

        if (bean.getType() == AppConstants.CHAT_TYPE_EVENT) {
            EventEntity eventEntity = new EventEntity(bean.getEventBean());
            eventDao = CarrefourRoomDatabase.getDatabase(App.getInstance()).eventDao();
            eventDao.insert(eventEntity);
        }
        if (bean.getType() == AppConstants.CHAT_TYPE_CONTACT) {
            ContactEntity contactEntity = new ContactEntity(bean.getContactBean());
            contactDao = CarrefourRoomDatabase.getDatabase(App.getInstance()).contactDao();
            contactDao.insert(contactEntity);
        }
        if (bean.getType() == AppConstants.CHAT_TYPE_POLL) {
            PollEntity pollEntity = new PollEntity(bean.getPollBean());
            pollDao = CarrefourRoomDatabase.getDatabase(App.getInstance()).pollDao();
            pollDao.insert(pollEntity);
        }

        // Inserting Row

        long result = db.insert(tableNamePrefix + tableName, null, values);
        db.close(); // Closing database connection
        return result != -1;
    }

    // Getting single chat
    @SuppressWarnings("unchecked")
    public ChatBean getChat(String id, String tableName, boolean isGroupChat) {
        checkDataBaseForTable(tableName, isGroupChat);
        String tableNamePrefix = getTableNamePrefix(isGroupChat);
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(tableNamePrefix + tableName,
                new String[]{
                        KEY_CHAT_ID,
                        KEY_CHAT_ORIGINAL_ID,
                        KEY_CHAT_TYPE,
                        KEY_CHAT_MESSAGE,
                        KEY_CHAT_IMAGE_URL,
                        KEY_CHAT_VIDEO_URL,
                        KEY_CHAT_VIDEO_DURATION,
                        KEY_CHAT_SNAPSHOT_URL,
                        KEY_CHAT_STICKER_URL,
                        KEY_CHAT_AUDIO_URL,
                        KEY_CHAT_DOCUMENT_URL,
                        KEY_CHAT_RECEIVER_ID,
                        KEY_CHAT_SENDER_ID,
                        KEY_CHAT_SENDER_NAME,
                        KEY_CHAT_RECEIVER_NAME,
                        KEY_CHAT_SENDER_PHOTO,
                        KEY_CHAT_RECEIVER_PHOTO,
                        KEY_CHAT_TIMESTAMP,
                        KEY_CHAT_TREE_TYPE,
                        KEY_CHAT_IS_TREE_CHAT,
                        KEY_CHAT_IS_GROUP_CHAT,
                        KEY_CHAT_IS_CORPORATE_TREE,
                        KEY_CHAT_IS_MINISTRY_TREE,
                        KEY_CHAT_GROUP_ID,
                        KEY_CHAT_EVENT_ID,
                        KEY_CHAT_POLL_ID,
                        KEY_CHAT_LOCATION_ID,
                        KEY_CHAT_CONTACT_ID,
                        KEY_CHAT_IS_READ,
                        KEY_CHAT_IS_SENT
                },
                KEY_CHAT_ID + "=?",
                new String[]{String.valueOf(id)}, null, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            cursor.moveToFirst();
            ChatBean chatBean = new ChatBean();

            chatBean.setId(cursor.getString(cursor.getColumnIndex(KEY_CHAT_ID)));
            chatBean.setOriginalID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_ORIGINAL_ID)));
            chatBean.setType(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_TYPE)));
            chatBean.setMessage(cursor.getString(cursor.getColumnIndex(KEY_CHAT_MESSAGE)));
            chatBean.setImageURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_IMAGE_URL)));
            chatBean.setVideoURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_VIDEO_URL)));
            chatBean.setVideoDuration(cursor.getLong(cursor.getColumnIndex(KEY_CHAT_VIDEO_DURATION)));
            chatBean.setSnapshotURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SNAPSHOT_URL)));
            chatBean.setStickerURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_STICKER_URL)));
            chatBean.setAudioURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_AUDIO_URL)));
            chatBean.setDocumentURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_DOCUMENT_URL)));
            chatBean.setReceiverID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_RECEIVER_ID)));
            chatBean.setSenderID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SENDER_ID)));
            chatBean.setSenderName(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SENDER_NAME)));
            chatBean.setReceiverName(cursor.getString(cursor.getColumnIndex(KEY_CHAT_RECEIVER_NAME)));
            chatBean.setSenderPhoto(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SENDER_PHOTO)));
            chatBean.setReceiverPhoto(cursor.getString(cursor.getColumnIndex(KEY_CHAT_RECEIVER_PHOTO)));
            chatBean.setTimestamp(cursor.getLong(cursor.getColumnIndex(KEY_CHAT_TIMESTAMP)));
            chatBean.setTreeType(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_TREE_TYPE)));
            chatBean.setTreeChat(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_TREE_CHAT)) == 1);
            chatBean.setGroupChat(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_GROUP_CHAT)) == 1);
            chatBean.setCorporateTree(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_CORPORATE_TREE)) == 1);
            chatBean.setMinistryTree(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_MINISTRY_TREE)) == 1);
            chatBean.setGroupID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_GROUP_ID)));
            chatBean.setEventID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_EVENT_ID)));
            chatBean.setPollID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_POLL_ID)));
            chatBean.setLocationID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_LOCATION_ID)));
            chatBean.setContactID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_CONTACT_ID)));
            chatBean.setRead(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_READ)) == 1);
            chatBean.setSent(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_SENT)) == 1);

            cursor.close();
            db.close();

            List<LocationEntity> locationEntities = locationDao.getLocation(chatBean.getId());
            if (!locationEntities.isEmpty()) {
                LocationEntity locationEntity = locationEntities.get(0);
                chatBean.setLocationBean(locationEntity.getBean());
            }

            List<EventEntity> eventEntities = eventDao.getEvent(chatBean.getEventID());
            if (!eventEntities.isEmpty()) {
                EventEntity eventEntity = eventEntities.get(0);
                chatBean.setEventBean(eventEntity.getBean());
            }
            List<ContactEntity> contactEntities = contactDao.getContact(chatBean.getContactID());
            if (!contactEntities.isEmpty()) {
                ContactEntity contactEntity = contactEntities.get(0);
                chatBean.setContactBean(contactEntity.getBean());
            }
            List<PollEntity> pollEntities = pollDao.getPoll(chatBean.getPollID());
            if (!pollEntities.isEmpty()) {
                PollEntity pollEntity = pollEntities.get(0);
                chatBean.setPollBean(pollEntity.getBean());
            }

            return chatBean;
        } else if (cursor != null) {
            cursor.close();
            db.close();
            return null;
        } else {
            db.close();
            return null;
        }

    }

    // Getting All Chats
    @SuppressWarnings("unchecked")
    public ChatListBean getChatList(int page, String tableName, boolean isGroupChat) {
        ChatListBean chatListBean = new ChatListBean();
        ArrayList<ChatBean> chatList = new ArrayList<>();
        // Select All Query
        checkDataBaseForTable(tableName, isGroupChat);
        String tableNamePrefix = getTableNamePrefix(isGroupChat);
        String selectQuery = "SELECT  * FROM " + tableNamePrefix + tableName
                + " ORDER BY " + KEY_CHAT_TIMESTAMP + " DESC LIMIT 20 OFFSET " + (page - 1) * 20;
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                ChatBean chatBean = new ChatBean();
                chatBean.setId(cursor.getString(cursor.getColumnIndex(KEY_CHAT_ID)));
                chatBean.setOriginalID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_ORIGINAL_ID)));
                chatBean.setType(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_TYPE)));
                chatBean.setMessage(cursor.getString(cursor.getColumnIndex(KEY_CHAT_MESSAGE)));
                chatBean.setImageURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_IMAGE_URL)));
                chatBean.setVideoURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_VIDEO_URL)));
                chatBean.setVideoDuration(cursor.getLong(cursor.getColumnIndex(KEY_CHAT_VIDEO_DURATION)));
                chatBean.setSnapshotURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SNAPSHOT_URL)));
                chatBean.setStickerURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_STICKER_URL)));
                chatBean.setAudioURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_AUDIO_URL)));
                chatBean.setDocumentURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_DOCUMENT_URL)));
                chatBean.setReceiverID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_RECEIVER_ID)));
                chatBean.setSenderID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SENDER_ID)));
                chatBean.setSenderName(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SENDER_NAME)));
                chatBean.setReceiverName(cursor.getString(cursor.getColumnIndex(KEY_CHAT_RECEIVER_NAME)));
                chatBean.setSenderPhoto(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SENDER_PHOTO)));
                chatBean.setReceiverPhoto(cursor.getString(cursor.getColumnIndex(KEY_CHAT_RECEIVER_PHOTO)));
                chatBean.setTimestamp(cursor.getLong(cursor.getColumnIndex(KEY_CHAT_TIMESTAMP)));
                chatBean.setTreeType(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_TREE_TYPE)));
                chatBean.setTreeChat(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_TREE_CHAT)) == 1);
                chatBean.setGroupChat(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_GROUP_CHAT)) == 1);
                chatBean.setCorporateTree(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_CORPORATE_TREE)) == 1);
                chatBean.setMinistryTree(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_MINISTRY_TREE)) == 1);
                chatBean.setGroupID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_GROUP_ID)));
                chatBean.setEventID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_EVENT_ID)));
                chatBean.setPollID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_POLL_ID)));
                chatBean.setLocationID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_LOCATION_ID)));
                chatBean.setContactID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_CONTACT_ID)));
                chatBean.setRead(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_READ)) == 1);
                chatBean.setSent(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_SENT)) == 1);

                List<LocationEntity> locationEntities = locationDao.getLocation(chatBean.getId());
                if (!locationEntities.isEmpty()) {
                    LocationEntity locationEntity = locationEntities.get(0);
                    chatBean.setLocationBean(locationEntity.getBean());
                }

                List<EventEntity> eventEntities = eventDao.getEvent(chatBean.getEventID());
                if (!eventEntities.isEmpty()) {
                    EventEntity eventEntity = eventEntities.get(0);
                    chatBean.setEventBean(eventEntity.getBean());
                }
                List<ContactEntity> contactEntities = contactDao.getContact(chatBean.getContactID());
                if (!contactEntities.isEmpty()) {
                    ContactEntity contactEntity = contactEntities.get(0);
                    chatBean.setContactBean(contactEntity.getBean());
                }
                List<PollEntity> pollEntities = pollDao.getPoll(chatBean.getPollID());
                if (!pollEntities.isEmpty()) {
                    PollEntity pollEntity = pollEntities.get(0);
                    chatBean.setPollBean(pollEntity.getBean());
                }

                chatList.add(0, chatBean);
            } while (cursor.moveToNext());
        }
        chatListBean.setChats(chatList);
        chatListBean.setPagination(getPagination(page, getChatCount(tableNamePrefix + tableName, isGroupChat)));

        cursor.close();
        db.close();
        return chatListBean;
    }

    // Getting All Unread Chats
    @SuppressWarnings("unchecked")
    public ChatListBean getUnreadChatList(String tableName, boolean isGroupChat) {
        ChatListBean chatListBean = new ChatListBean();
        ArrayList<ChatBean> chatList = new ArrayList<>();
        // Select All Query
        checkDataBaseForTable(tableName, isGroupChat);
        String tableNamePrefix = getTableNamePrefix(isGroupChat);
        String selectQuery = "SELECT  * FROM " + tableNamePrefix + tableName + " WHERE " + KEY_CHAT_IS_READ + " = 1"
                + " ORDER BY " + KEY_CHAT_TIMESTAMP + " DESC";
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                ChatBean chatBean = new ChatBean();
                chatBean.setId(cursor.getString(cursor.getColumnIndex(KEY_CHAT_ID)));
                chatBean.setOriginalID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_ORIGINAL_ID)));
                chatBean.setType(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_TYPE)));
                chatBean.setMessage(cursor.getString(cursor.getColumnIndex(KEY_CHAT_MESSAGE)));
                chatBean.setImageURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_IMAGE_URL)));
                chatBean.setVideoURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_VIDEO_URL)));
                chatBean.setVideoDuration(cursor.getLong(cursor.getColumnIndex(KEY_CHAT_VIDEO_DURATION)));
                chatBean.setSnapshotURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SNAPSHOT_URL)));
                chatBean.setStickerURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_STICKER_URL)));
                chatBean.setAudioURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_AUDIO_URL)));
                chatBean.setDocumentURL(cursor.getString(cursor.getColumnIndex(KEY_CHAT_DOCUMENT_URL)));
                chatBean.setReceiverID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_RECEIVER_ID)));
                chatBean.setSenderID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SENDER_ID)));
                chatBean.setSenderName(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SENDER_NAME)));
                chatBean.setReceiverName(cursor.getString(cursor.getColumnIndex(KEY_CHAT_RECEIVER_NAME)));
                chatBean.setSenderPhoto(cursor.getString(cursor.getColumnIndex(KEY_CHAT_SENDER_PHOTO)));
                chatBean.setReceiverPhoto(cursor.getString(cursor.getColumnIndex(KEY_CHAT_RECEIVER_PHOTO)));
                chatBean.setTimestamp(cursor.getLong(cursor.getColumnIndex(KEY_CHAT_TIMESTAMP)));
                chatBean.setTreeType(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_TREE_TYPE)));
                chatBean.setTreeChat(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_TREE_CHAT)) == 1);
                chatBean.setGroupChat(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_GROUP_CHAT)) == 1);
                chatBean.setCorporateTree(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_CORPORATE_TREE)) == 1);
                chatBean.setMinistryTree(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_MINISTRY_TREE)) == 1);
                chatBean.setGroupID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_GROUP_ID)));
                chatBean.setEventID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_EVENT_ID)));
                chatBean.setPollID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_POLL_ID)));
                chatBean.setLocationID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_LOCATION_ID)));
                chatBean.setContactID(cursor.getString(cursor.getColumnIndex(KEY_CHAT_CONTACT_ID)));
                chatBean.setRead(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_READ)) == 1);
                chatBean.setSent(cursor.getInt(cursor.getColumnIndex(KEY_CHAT_IS_SENT)) == 1);

                List<LocationEntity> locationEntities = locationDao.getLocation(chatBean.getId());
                if (!locationEntities.isEmpty()) {
                    LocationEntity locationEntity = locationEntities.get(0);
                    chatBean.setLocationBean(locationEntity.getBean());
                }

                List<EventEntity> eventEntities = eventDao.getEvent(chatBean.getEventID());
                if (!eventEntities.isEmpty()) {
                    EventEntity eventEntity = eventEntities.get(0);
                    chatBean.setEventBean(eventEntity.getBean());
                }
                List<ContactEntity> contactEntities = contactDao.getContact(chatBean.getContactID());
                if (!contactEntities.isEmpty()) {
                    ContactEntity contactEntity = contactEntities.get(0);
                    chatBean.setContactBean(contactEntity.getBean());
                }
                List<PollEntity> pollEntities = pollDao.getPoll(chatBean.getPollID());
                if (!pollEntities.isEmpty()) {
                    PollEntity pollEntity = pollEntities.get(0);
                    chatBean.setPollBean(pollEntity.getBean());
                }

                chatList.add(0, chatBean);
            } while (cursor.moveToNext());
        }
        chatListBean.setChats(chatList);
        chatListBean.setPagination(getPagination(0, getChatCount(tableNamePrefix + tableName, isGroupChat)));

        cursor.close();
        db.close();
        return chatListBean;
    }


    // Updating single chatBean
    public boolean updateChat(String tableName, ChatBean bean, boolean isGroupChat) {

        checkDataBaseForTable(tableName, isGroupChat);
        String tableNamePrefix = getTableNamePrefix(isGroupChat);

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_CHAT_ID, bean.getId());
        values.put(KEY_CHAT_ORIGINAL_ID, bean.getOriginalID());
        values.put(KEY_CHAT_TYPE, bean.getType());
        values.put(KEY_CHAT_MESSAGE, bean.getMessage());
        values.put(KEY_CHAT_IMAGE_URL, bean.getImageURL());
        values.put(KEY_CHAT_VIDEO_URL, bean.getVideoURL());
        values.put(KEY_CHAT_VIDEO_DURATION, bean.getVideoDuration());
        values.put(KEY_CHAT_SNAPSHOT_URL, bean.getSnapshotURL());
        values.put(KEY_CHAT_STICKER_URL, bean.getStickerURL());
        values.put(KEY_CHAT_AUDIO_URL, bean.getAudioURL());
        values.put(KEY_CHAT_DOCUMENT_URL, bean.getDocumentURL());
        values.put(KEY_CHAT_RECEIVER_ID, bean.getReceiverID());
        values.put(KEY_CHAT_SENDER_ID, bean.getSenderID());
        values.put(KEY_CHAT_SENDER_NAME, bean.getSenderName());
        values.put(KEY_CHAT_RECEIVER_NAME, bean.getReceiverName());
        values.put(KEY_CHAT_SENDER_PHOTO, bean.getSenderPhoto());
        values.put(KEY_CHAT_RECEIVER_PHOTO, bean.getReceiverPhoto());
        values.put(KEY_CHAT_TIMESTAMP, bean.getTimestamp());
        values.put(KEY_CHAT_TREE_TYPE, bean.getTreeType());
        values.put(KEY_CHAT_IS_TREE_CHAT, bean.isTreeChat());
        values.put(KEY_CHAT_IS_GROUP_CHAT, bean.isGroupChat());
        values.put(KEY_CHAT_IS_CORPORATE_TREE, bean.isCorporateTree());
        values.put(KEY_CHAT_IS_MINISTRY_TREE, bean.isMinistryTree());
        values.put(KEY_CHAT_GROUP_ID, bean.getGroupID());
        values.put(KEY_CHAT_EVENT_ID, bean.getEventID());
        values.put(KEY_CHAT_POLL_ID, bean.getPollID());
        values.put(KEY_CHAT_LOCATION_ID, bean.getLocationID());
        values.put(KEY_CHAT_CONTACT_ID, bean.getContactID());
        values.put(KEY_CHAT_IS_READ, bean.isRead());
        values.put(KEY_CHAT_IS_SENT, bean.isSent());

        if (bean.getType() == AppConstants.CHAT_TYPE_LOCATION) {
            LocationEntity locationEntity = new LocationEntity(bean.getLocationBean());
            locationDao = CarrefourRoomDatabase.getDatabase(App.getInstance()).locationDao();
            locationDao.insert(locationEntity);
        }

        if (bean.getType() == AppConstants.CHAT_TYPE_EVENT) {
            EventEntity eventEntity = new EventEntity(bean.getEventBean());
            eventDao = CarrefourRoomDatabase.getDatabase(App.getInstance()).eventDao();
            eventDao.insert(eventEntity);
        }
        if (bean.getType() == AppConstants.CHAT_TYPE_CONTACT) {
            ContactEntity contactEntity = new ContactEntity(bean.getContactBean());
            contactDao = CarrefourRoomDatabase.getDatabase(App.getInstance()).contactDao();
            contactDao.insert(contactEntity);
        }
        if (bean.getType() == AppConstants.CHAT_TYPE_POLL) {
            PollEntity pollEntity = new PollEntity(bean.getPollBean());
            pollDao = CarrefourRoomDatabase.getDatabase(App.getInstance()).pollDao();
            pollDao.insert(pollEntity);
        }

        // Updating Row
        db.update(tableNamePrefix + tableName, values, KEY_CHAT_ID + " = ?",
                new String[]{String.valueOf(bean.getId())});

        db.close(); // Closing database connection
        return true;
    }

    // Deleting single Chat
    public boolean deleteChat(String tableName, ChatBean bean, boolean isFriendChat) {

        checkDataBaseForTable(tableName, isFriendChat);
        String tableNamePrefix = getTableNamePrefix(isFriendChat);
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(tableNamePrefix + tableName, KEY_CHAT_ID + " = ?",
                new String[]{String.valueOf(bean.getId())});
        db.close();

        return true;
    }

    public boolean deleteAllChats(String tableName, boolean isFriendChat) {
        checkDataBaseForTable(tableName, isFriendChat);
        String tableNamePrefix = getTableNamePrefix(isFriendChat);

        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(tableNamePrefix + tableName, null, null);
        db.close();

        return true;
    }


    // Getting ChatList Count
    private int getChatCount(String tableName, boolean isFriendChat) {
        checkDataBaseForTable(tableName, isFriendChat);
        int count = 0;
        String tableNamePrefix = getTableNamePrefix(isFriendChat);


        String countQuery = "SELECT  * FROM " + tableNamePrefix + tableName;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        count = cursor.getCount();
        cursor.close();
        return count;
    }


    @NonNull
    private String getTableNamePrefix(boolean isGroupChat) {
        String tableNamePrefix = "";
        if (!isGroupChat) {
            tableNamePrefix = PREFIX_TABLE_NAME_PRIVATE_CHAT;
        } else {
            tableNamePrefix = PREFIX_TABLE_NAME_GROUP_CHAT;
        }
        return tableNamePrefix;
    }

    private void checkDataBaseForTable(String tableName, boolean isGroupChat) {
        SQLiteDatabase db = this.getWritableDatabase();
        String tableNamePrefix = getTableNamePrefix(isGroupChat);
        String query = PREFIX_CREATE_TABLE_IF_NOT_EXISTS + tableNamePrefix + tableName + SUFFIX_CREATE_CHAT_LIST_TABLE;
        db.execSQL(query);
        db = this.getWritableDatabase();
        db.close();
    }

    private PaginationBean getPagination(int page, int itemCount) {
        int pageCount = 0;

        pageCount = itemCount / 20;
        if (itemCount % 20 != 0)
            pageCount += 1;

        PaginationBean pagination = new PaginationBean();
        pagination.setCurrentPage(page);
        pagination.setTotalCount(itemCount);
        pagination.setTotalPages(pageCount);

        System.out.println("TOTAL COUNT : " + itemCount + " \nPAGE COUNT : " + pageCount + "\nCurrent Page : " + page);

        return pagination;
    }*/

}
