package com.example.myapplication.DataBase;

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

import com.example.myapplication.model.Project;

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

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "UserDB";
    private static final int DATABASE_VERSION = 3;
    private static final String TABLE_USERS = "users";
    private static final String TABLE_PROJECTS = "projects";

    // 用户表列名
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_PASSWORD = "password";
    public static final String COLUMN_USER_PROJECT_ID = "user_project_id";
    public static final String COLUMN_USER_PROJECT_NAME = "user_project_name";

    // 项目表列名
    public static final String COLUMN_PROJECT_ID = "project_id";
    public static final String COLUMN_PROJECT_NAME = "project_name";
    public static final String COLUMN_LAST_UPDATED = "last_updated";

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

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建用户表
        String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_USERNAME + " TEXT UNIQUE,"
                + COLUMN_PASSWORD + " TEXT,"
                + COLUMN_USER_PROJECT_ID + " TEXT,"
                + COLUMN_USER_PROJECT_NAME + " TEXT" + ")";
        db.execSQL(CREATE_USERS_TABLE);

        // 创建项目表
        String CREATE_PROJECTS_TABLE = "CREATE TABLE " + TABLE_PROJECTS + "("
                + COLUMN_PROJECT_ID + " TEXT PRIMARY KEY,"
                + COLUMN_PROJECT_NAME + " TEXT,"
                + COLUMN_LAST_UPDATED + " INTEGER" + ")";
        db.execSQL(CREATE_PROJECTS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < 2) {
            // 版本1到版本2的迁移
            db.execSQL("CREATE TABLE " + TABLE_USERS + "_temp" + "("
                    + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + COLUMN_USERNAME + " TEXT UNIQUE,"
                    + COLUMN_PASSWORD + " TEXT,"
                    + COLUMN_USER_PROJECT_ID + " TEXT" + ")");

            db.execSQL("INSERT INTO " + TABLE_USERS + "_temp ("
                    + COLUMN_USERNAME + ", " + COLUMN_PASSWORD + ", " + COLUMN_USER_PROJECT_ID + ") "
                    + "SELECT username, password, project FROM " + TABLE_USERS);

            db.execSQL("DROP TABLE " + TABLE_USERS);
            db.execSQL("ALTER TABLE " + TABLE_USERS + "_temp RENAME TO " + TABLE_USERS);
        }

        if (oldVersion < 3) {
            // 版本2到版本3的迁移，添加项目名称列
            db.execSQL("ALTER TABLE " + TABLE_USERS + " ADD COLUMN " + COLUMN_USER_PROJECT_NAME + " TEXT");
        }
    }

    // 用户操作方法
    public boolean addUser(String username, String password, String projectId, String projectName) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_USERNAME, username);
        values.put(COLUMN_PASSWORD, password);
        values.put(COLUMN_USER_PROJECT_ID, projectId);
        values.put(COLUMN_USER_PROJECT_NAME, projectName);

        long result = db.insert(TABLE_USERS, null, values);
        db.close();
        return result != -1;
    }

    public boolean updateUserProject(String username, String newProjectId, String newProjectName) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_PROJECT_ID, newProjectId);
        values.put(COLUMN_USER_PROJECT_NAME, newProjectName);
        int result = db.update(TABLE_USERS, values,
                COLUMN_USERNAME + " = ?",
                new String[]{username});
        db.close();
        return result > 0;
    }

    public Cursor getAllUsers() {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.query(TABLE_USERS,
                new String[]{COLUMN_ID, COLUMN_USERNAME, COLUMN_PASSWORD,
                        COLUMN_USER_PROJECT_ID, COLUMN_USER_PROJECT_NAME},
                null, null, null, null, null);
    }

    public boolean deleteUser(String username) {
        SQLiteDatabase db = this.getWritableDatabase();
        int result = db.delete(TABLE_USERS,
                COLUMN_USERNAME + " = ?",
                new String[]{username});
        db.close();
        return result > 0;
    }

    public boolean checkUser(String username, String password) {
        SQLiteDatabase db = this.getReadableDatabase();
        String[] columns = {COLUMN_ID};
        String selection = COLUMN_USERNAME + " = ? AND " + COLUMN_PASSWORD + " = ?";
        String[] selectionArgs = {username, password};

        Cursor cursor = db.query(TABLE_USERS, columns, selection, selectionArgs,
                null, null, null);
        int count = cursor.getCount();
        cursor.close();
        db.close();
        return count > 0;
    }

    public boolean userExists(String username) {
        SQLiteDatabase db = this.getReadableDatabase();
        String[] columns = {COLUMN_ID};
        String selection = COLUMN_USERNAME + " = ?";
        String[] selectionArgs = {username};

        Cursor cursor = db.query(TABLE_USERS, columns, selection, selectionArgs,
                null, null, null);
        int count = cursor.getCount();
        cursor.close();
        db.close();
        return count > 0;
    }

    // 项目操作方法
    public void saveProjects(List<Project> projects) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        try {
            db.delete(TABLE_PROJECTS, null, null);

            for (Project project : projects) {
                ContentValues values = new ContentValues();
                values.put(COLUMN_PROJECT_ID, project.getProjectId());
                values.put(COLUMN_PROJECT_NAME, project.getProjectName());
                values.put(COLUMN_LAST_UPDATED, System.currentTimeMillis());
                db.insert(TABLE_PROJECTS, null, values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    public List<Project> getAllProjects() {
        List<Project> projects = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_PROJECTS,
                new String[]{COLUMN_PROJECT_ID, COLUMN_PROJECT_NAME},
                null, null, null, null, COLUMN_PROJECT_NAME + " ASC");

        if (cursor.moveToFirst()) {
            do {
                Project project = new Project(
                        cursor.getString(0),
                        cursor.getString(1)
                );
                projects.add(project);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return projects;
    }

    public List<Project> searchProjects(String query) {
        List<Project> projects = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_PROJECT_NAME + " LIKE ? OR " + COLUMN_PROJECT_ID + " LIKE ?";
        String[] selectionArgs = new String[]{"%" + query + "%", "%" + query + "%"};

        Cursor cursor = db.query(TABLE_PROJECTS,
                new String[]{COLUMN_PROJECT_ID, COLUMN_PROJECT_NAME},
                selection, selectionArgs, null, null, COLUMN_PROJECT_NAME + " ASC");

        if (cursor.moveToFirst()) {
            do {
                Project project = new Project(
                        cursor.getString(0),
                        cursor.getString(1)
                );
                projects.add(project);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return projects;
    }
    public void updateLastUpdateTime(long time) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("last_update_time", time);

        // 更新或插入最后更新时间
        db.insertWithOnConflict("app_settings", null, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.close();
    }

    // 添加这个方法

    public long getLastUpdateTime() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_PROJECTS,
                new String[]{"MAX(" + COLUMN_LAST_UPDATED + ")"},
                null, null, null, null, null);

        long lastUpdated = 0;
        if (cursor.moveToFirst()) {
            lastUpdated = cursor.getLong(0);
        }
        cursor.close();
        return lastUpdated;
    }
}