package com.example.myapplication.repository;

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

import com.example.myapplication.domain.Major;

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

public class MajorRepository {
    private final Context context;
    private DatabaseHelper helper;
    private SQLiteDatabase db;

    public MajorRepository(Context context) { this.context = context.getApplicationContext(); }

    public void openDatabase() {
        if (helper == null) helper = new DatabaseHelper(context);
        if (db == null || !db.isOpen()) db = helper.getWritableDatabase();
    }

    public void closeDatabase() { if (db != null && db.isOpen()) db.close(); db = null; }

    public List<Major> findByNameLike(String keywords, int limit) {
        openDatabase();
        List<Major> list = new ArrayList<>();
        String like = "%" + (keywords == null ? "" : keywords.trim()) + "%";
        try (Cursor c = db.query("T_Major", null, "name LIKE ? OR code LIKE ?",
                new String[]{like, like}, null, null, "name ASC", String.valueOf(Math.max(1, limit)) )) {
            while (c != null && c.moveToNext()) list.add(map(c));
        }
        closeDatabase();
        return list;
    }

    public Major getById(long id) {
        openDatabase();
        Major m = null;
        try (Cursor c = db.query("T_Major", null, "id=?", new String[]{String.valueOf(id)}, null, null, null)) {
            if (c != null && c.moveToFirst()) m = map(c);
        }
        closeDatabase();
        return m;
    }

    private Major map(Cursor c) {
        return new Major(
                c.getLong(c.getColumnIndexOrThrow("id")),
                c.getString(c.getColumnIndexOrThrow("name")),
                c.getString(c.getColumnIndexOrThrow("code")),
                c.getString(c.getColumnIndexOrThrow("description"))
        );
    }
}