package ai.pai.lensman.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.android.common.utils.LogHelper;

import java.util.ArrayList;

import ai.pai.lensman.App;
import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.bean.SessionBean;


public class DBService {

    private static DBService instance;
    private static Object DB_LOCK = new Object();
    private DBHelper dbHelper;

    private static final String TAG = "DBService";

    private DBService(Context context) {
        dbHelper = DBHelper.getInstance(context);
    }

    public static synchronized DBService getInstance() {
        if (instance == null) {
            instance = new DBService(App.getAppContext());
        }
        return instance;
    }

    private void closeDB(SQLiteDatabase db) {
        if (db != null) {
            db.close();
        }
    }

    private void closeCursorAndDB(Cursor cursor, SQLiteDatabase db) {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
        if (db != null) {
            db.close();
        }
    }

    public void clearDB(){
        SQLiteDatabase db = null;
        try{
            db = dbHelper.getReadableDatabase();
            db.beginTransaction();
            db.execSQL("delete from "+ DBHelper.PHOTO_INFO_TABLE);
        }catch (Exception e){
            LogHelper.e(TAG,"clear db ,error occurs "+e);
        }finally {
            try {
                db.endTransaction();
            } catch (Exception e) {
                e.printStackTrace();
            }
            closeDB(db);
        }
    }

    private PhotoBean cursor2PhotoBean(Cursor c) {
        PhotoBean item = new PhotoBean();
        item.lensmanId = c.getString(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.LENSMAN_ID));
        item.sessionId = c.getString(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.SESSION_ID));
        item.isRawPhoto =(c.getInt(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.IS_RAW_PHOTO))>0);
        item.uploadStatus = c.getInt(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.UPLOADED_STATUS));
        item.captureTime = c.getLong(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.CAPTURE_TIME));
        item.photoId = c.getLong(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.PHOTO_ID));
        item.photoName = c.getString(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.PHOTO_NAME));
        item.photoPath = c.getString(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.PHOTO_PATH));
        item.sessionDate = c.getLong(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.SESSION_DATE));
        item.sessionSeq = c.getInt(c.getColumnIndex(DBHelper.PHOTO_INFO_COLUMNS.SESSION_SEQ));
        return item;
    }

    private ContentValues photoBean2ContentValues(PhotoBean item) {
        ContentValues cv = new ContentValues();
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.CAPTURE_TIME, item.captureTime);
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.IS_RAW_PHOTO, item.isRawPhoto ? 1: 0);
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.PHOTO_ID, item.photoId);
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.PHOTO_NAME, item.photoName);
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.PHOTO_PATH, item.photoPath);
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.SESSION_ID, item.sessionId);
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.LENSMAN_ID,item.lensmanId);
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.UPLOADED_STATUS,item.uploadStatus);
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.SESSION_DATE,item.sessionDate);
        cv.put(DBHelper.PHOTO_INFO_COLUMNS.SESSION_SEQ,item.sessionSeq);
        return cv;
    }

    public void addPhotoBean(PhotoBean bean){
        SQLiteDatabase db = null;
        synchronized (DB_LOCK) {
            try {
                db = dbHelper.getWritableDatabase();
                db.beginTransaction();
                db.insertWithOnConflict(DBHelper.PHOTO_INFO_TABLE, null, photoBean2ContentValues(bean),
                        SQLiteDatabase.CONFLICT_REPLACE);
                db.setTransactionSuccessful();
            } catch (Exception e) {
                LogHelper.d(TAG, "dbservice addUploadPhoto error happen " + e);
            } finally {
                try {
                    db.endTransaction();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                closeDB(db);
            }
        }
    }

    public void updatePhotoBean(PhotoBean bean){
        addPhotoBean(bean);
    }

    public void deletePhotoBean(PhotoBean bean){
        SQLiteDatabase db = null;
        synchronized (DB_LOCK) {
            try {
                db = dbHelper.getReadableDatabase();
                db.beginTransaction();
                db.execSQL("delete  from " + DBHelper.PHOTO_INFO_TABLE + " where "
                        + DBHelper.PHOTO_INFO_COLUMNS.PHOTO_PATH + " = '" + bean.photoPath + "'");
                db.setTransactionSuccessful();
            } catch (Exception e) {
                LogHelper.d(TAG, "dbservice deleteUploadPhoto error happen " + e);
            } finally {
                try {
                    db.endTransaction();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                closeCursorAndDB(null, db);
            }
        }
    }

    public ArrayList<SessionBean> getSessionBeanListByDay(long sessionDate){
        ArrayList<SessionBean> sessionBeanArrayList = new ArrayList<>();
        SQLiteDatabase db = null;
        Cursor c = null;
        synchronized (DB_LOCK) {
            try {
                db = dbHelper.getReadableDatabase();
                db.beginTransaction();
                c = db.rawQuery("select * from " + DBHelper.PHOTO_INFO_TABLE + " where "
                        + DBHelper.PHOTO_INFO_COLUMNS.SESSION_DATE + " = '" + sessionDate + "' order by " + DBHelper.PHOTO_INFO_COLUMNS.SESSION_SEQ + " desc", null);
                while (c.moveToNext()) {
                    PhotoBean photoBean = cursor2PhotoBean(c);
                    if(sessionBeanArrayList.size()==0 || sessionBeanArrayList.get(sessionBeanArrayList.size()-1).sessionSeq!=photoBean.sessionSeq){
                        SessionBean sessionBean = new SessionBean();
                        sessionBean.sessionDate = photoBean.sessionDate;
                        sessionBean.sessionSeq = photoBean.sessionSeq;
                        sessionBean.sessionId = photoBean.sessionId;
                        sessionBean.lensmanId = photoBean.lensmanId;
                        ArrayList<PhotoBean> photoList = new ArrayList<>();
                        sessionBean.sessionPhotos = photoList;
                        sessionBeanArrayList.add(sessionBean);
                    }
                    sessionBeanArrayList.get(sessionBeanArrayList.size()-1).sessionPhotos.add(photoBean);
                }
                db.setTransactionSuccessful();
            } catch (Exception e) {
                LogHelper.d(TAG, "dbservice getSessionBeanListByDay error happen " + e);
            } finally {
                try {
                    db.endTransaction();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                closeCursorAndDB(c, db);
            }
        }
        return sessionBeanArrayList;
    }

    public ArrayList<PhotoBean> getPhotoListBySessionId(String sessionId){
        SQLiteDatabase db = null;
        Cursor c = null;
        ArrayList<PhotoBean> photoList = new ArrayList<>();

        synchronized (DB_LOCK) {
            try {
                db = dbHelper.getReadableDatabase();
                db.beginTransaction();
                c = db.rawQuery("select * from " + DBHelper.PHOTO_INFO_TABLE + " where "
                        + DBHelper.PHOTO_INFO_COLUMNS.SESSION_ID + " = '" + sessionId + "'", null);
                while (c.moveToNext()) {
                    photoList.add(cursor2PhotoBean(c));
                }
                db.setTransactionSuccessful();
            } catch (Exception e) {
                LogHelper.d(TAG, "dbservice getGroupInfoByGroupId error happen " + e);
            } finally {
                try {
                    db.endTransaction();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                closeCursorAndDB(c, db);
            }
        }
        return photoList;
    }

    public PhotoBean getNextUploadPhoto(){
        LogHelper.d(TAG, "dbservice getNextUploadPhotoBean ");
        PhotoBean photoBean = null;
        SQLiteDatabase db = null;
        Cursor c = null;
        synchronized (DB_LOCK) {
            try {
                db = dbHelper.getReadableDatabase();
                db.beginTransaction();
                c = db.rawQuery("select * from " + DBHelper.PHOTO_INFO_TABLE +  " where "
                        + DBHelper.PHOTO_INFO_COLUMNS.UPLOADED_STATUS + " = '" + 0 + "'"+"  order by "
                        + DBHelper.PHOTO_INFO_COLUMNS.CAPTURE_TIME + " desc limit 1 ", null);
                if (c.moveToNext()) {
                    photoBean = cursor2PhotoBean(c);
                }
//                else {
//                    c = db.rawQuery("select * from " + DBHelper.PHOTO_INFO_TABLE +  " where "
//                            + DBHelper.PHOTO_INFO_COLUMNS.UPLOADED_STATUS + " = '" + -1 + "'"+"  order by "
//                            + DBHelper.PHOTO_INFO_COLUMNS.CAPTURE_TIME + " desc limit 1 ", null);
//                    if (c.moveToNext()) {
//                        photoBean = cursor2PhotoBean(c);
//                    }
//                }
                db.setTransactionSuccessful();
            } catch (Exception e) {
                LogHelper.d(TAG, "dbservice getNextUploadPhotoBean error happen " + e);
            } finally {
                try {
                    db.endTransaction();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                closeCursorAndDB(c, db);
            }
        }
        return photoBean;
    }

}
