package com.assimilate.alltrans.mydb;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;

import com.assimilate.alltrans.common.Logger;

import java.util.ArrayList;
import java.util.Collections;

public class DbTranslation extends SQLiteOpenHelper {
    private final static String TABLE = "trans";

    public DbTranslation(@NonNull final Context mContext) {
        super(mContext, "trw_trans_log.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE IF NOT EXISTS " + TABLE + " (" +
                "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
                "source_lan TEXT, " +
                "source_txt TEXT, " +
                "target_lan TEXT, " +
                "target_txt TEXT, " +
                "current_time_millis INTEGER, " +
                "exist INTEGER DEFAULT 1, " +
                "collection INTEGER DEFAULT 0);"
        );
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE);
        onCreate(db);
    }

    /**
     * 新增一条翻译记录
     * @param translations 翻译记录
     */
    public boolean addTranslation(Translations translations) {
        if (null == translations) return false;

        final String sourceLanguage = translations.getSourceLanguage();
        if (TextUtils.isEmpty(sourceLanguage)) return false;

        final String sourceText = translations.getSourceTxt().trim();
        if (TextUtils.isEmpty(sourceText)) return false;

        final String targetLanguage = translations.getTargetLanguage();
        if (TextUtils.isEmpty(targetLanguage)) return false;

        final String targetTxt = translations.getTargetTxt().trim();
        if (TextUtils.isEmpty(targetTxt)) return false;

        try (SQLiteDatabase sqLiteDatabase = getWritableDatabase()) {
            ContentValues contentValues = new ContentValues();
            contentValues.put("source_lan", sourceLanguage);
            contentValues.put("source_txt", sourceText);
            contentValues.put("target_lan", targetLanguage);
            contentValues.put("target_txt", targetTxt);
            contentValues.put("current_time_millis", System.currentTimeMillis());

            long insert = sqLiteDatabase.insert(TABLE, null, contentValues);
            Logger.d("insert", "response: " + insert);

            return -1 != insert;
        } catch (Exception exception) {
            Log.d("SQLite: ", "at addTranslation: " + exception.getMessage());
            return false;
        }
    }

    /**
     * 移除翻译记录
     * @param ids {id...}
     */
    public void removeTranslations(ArrayList<Long> ids) {
        if (null == ids || ids.isEmpty()) return;
        try (SQLiteDatabase database = getWritableDatabase()) {
            ContentValues values = new ContentValues();
            values.put("exist", 0);
            for (Long id : ids) {
                database.update(TABLE, values, "id = ?", new String[]{String.valueOf(id)});
            }
        } catch (Exception exception) {
            Log.d("SQLite: ", "at removeTranslations: " + exception.getMessage());
        }
    }

    /**
     * 移除收藏记录
     * @param ids {id...}
     */
    public void removeCollectTranslations(ArrayList<Long> ids) {
        if (null == ids || ids.isEmpty()) return;
        try (SQLiteDatabase database = getWritableDatabase()) {
            ContentValues values = new ContentValues();
            values.put("collection", 0);
            for (Long id : ids) {
                database.update(TABLE, values, "id = ?", new String[]{String.valueOf(id)});
            }
        } catch (Exception exception) {
            Log.d("SQLite: ", "at removeTranslations: " + exception.getMessage());
        }
    }
    /**
     * 收藏｜不收藏
     */
    public boolean toggleCollect() {
        try (SQLiteDatabase database = getWritableDatabase();
             Cursor cursor = database.rawQuery("SELECT collection FROM " + TABLE + " ORDER BY id DESC LIMIT 1", null)) {

            if (cursor.moveToFirst()) {
                int collectionIndex = cursor.getColumnIndex("collection");
                if (collectionIndex != -1) {
                    int currentValue = cursor.getInt(collectionIndex);
                    int newValue = (currentValue == 1) ? 0 : 1;

                    ContentValues values = new ContentValues();
                    values.put("collection", newValue);
                    String selection = "id = (SELECT MAX(id) FROM " + TABLE + ")";
                    int result = database.update(TABLE, values, selection, null);

                    if (result > 0) {
                        try (Cursor checkCursor = database.rawQuery("SELECT collection FROM " + TABLE + " WHERE id = (SELECT MAX(id) FROM " + TABLE + ")", null)) {
                            if (checkCursor.moveToFirst()) {
                                int checkCollectionIndex = checkCursor.getColumnIndex("collection");
                                if (checkCollectionIndex != -1) {
                                    return checkCursor.getInt(checkCollectionIndex) == 1;
                                }
                            }
                        }
                    }
                }
            }
            return false;
        } catch (Exception exception) {
            Log.e("SQLite: ", "at toggleCollect: " + exception.getMessage());
            return false;
        }
    }

    /**
     * 检查最后一个翻译是否被收藏
     */
    public boolean isLastTranslationCollected() {
        try (SQLiteDatabase database = getWritableDatabase();
             Cursor cursor = database.rawQuery("SELECT collection FROM " + TABLE + " ORDER BY id DESC LIMIT 1", null)) {

            if (cursor.moveToFirst()) {
                int collectionIndex = cursor.getColumnIndex("collection");
                if (collectionIndex != -1) {
                    int collection = cursor.getInt(collectionIndex);
                    Log.d("SQLite: ", "Last translation collection value: " + collection);
                    return collection == 1;
                }
            } else {
                Log.d("SQLite: ", "No translations found.");
            }
        } catch (Exception exception) {
            Log.e("SQLite: ", "at isLastTranslationCollected: " + exception.getMessage());
        }
        return false;
    }

    /**
     * 得到翻译记录
     * @param filterCollect 是否需要过滤掉没有收藏的记录
     */
    public ArrayList<Translations>  getTranslations(boolean filterCollect) {
        final ArrayList<Translations> logs = new ArrayList<>();
        Cursor cursor = null;
        try (SQLiteDatabase database = getWritableDatabase();) {
            final String sql = "SELECT id, source_lan, source_txt, target_lan, target_txt, " +
                    "current_time_millis, exist, collection FROM " + TABLE;
            String selection = "exist = ?";
            String[] selectionArgs = {"1"};
            cursor = database.rawQuery(sql + " WHERE " + selection, selectionArgs);

            if (cursor != null) {
                final int idIndex = cursor.getColumnIndex("id");
                final int sourceLanIndex = cursor.getColumnIndex("source_lan");
                final int sourceTxtIndex = cursor.getColumnIndex("source_txt");
                final int targetLanIndex = cursor.getColumnIndex("target_lan");
                final int targetTxtIndex = cursor.getColumnIndex("target_txt");
                final int currentTimeMillisIndex = cursor.getColumnIndex("current_time_millis");
                final int existIndex = cursor.getColumnIndex("exist");
                final int collectionIndex = cursor.getColumnIndex("collection");

                if (cursor.moveToFirst()) {
                    do {
                        if (idIndex != -1) {
                            long id = cursor.getInt(idIndex);
                            String sourceLanguage = cursor.getString(sourceLanIndex);
                            String sourceText = cursor.getString(sourceTxtIndex);
                            String targetLanguage = cursor.getString(targetLanIndex);
                            String targetText = cursor.getString(targetTxtIndex);
                            long currentTimeMillis = cursor.getLong(currentTimeMillisIndex);
                            int exist = cursor.getInt(existIndex);
                            int collection = cursor.getInt(collectionIndex);

                            if (exist == 1) {
                                // 是否需要过滤掉没有收藏的简便写法
                                if (!filterCollect || collection == 1) {
                                    Translations translations = new Translations(id, sourceLanguage, sourceText, targetLanguage, targetText, currentTimeMillis, exist, collection);
                                    logs.add(translations);
                                }
                            }

                        }
                    } while (cursor.moveToNext());
                }

            }
        } catch (Exception exception) {
            Log.d("SQLite: ", "at getHistory: " + exception.getMessage());
        } finally {
            if (null != cursor) {
                cursor.close();
            }
        }
        Collections.reverse(logs);
        return logs;
    }

}
