package com.hjx.miaohongentry.db;

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

import com.hjx.miaohongentry.activity.InitCallback;
import com.hjx.miaohongentry.bean.BookInfo;
import com.hjx.miaohongentry.bean.RowWord;
import com.hjx.miaohongentry.bean.TitleWord;
import com.hjx.miaohongentry.util.Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by l on 2018/2/2.
 */

public class MHDataManager {

    public static ArrayList<BookInfo> getList(String dataPath){
        SQLiteDatabase mDB = null;
        List<BookInfo> mList = new ArrayList<BookInfo>();
        Cursor mCursor = null;

        mDB = SQLiteDatabase.openDatabase(dataPath, null,
                SQLiteDatabase.OPEN_READONLY);
        mCursor = mDB.rawQuery("select DISTINCT * from " + MHDataTable.DATA_BOOK_TABLE_NAME,null);
        if (mCursor != null) {
            int count = 0;
            while (mCursor.moveToNext()) {
                BookInfo tDetailInfo = getBookInfo(mCursor,count);
                mList.add(tDetailInfo);
                count++;
            }
            mCursor.close();
        }

        mDB.close();

        return (ArrayList<BookInfo>) mList;
    }


    private static BookInfo getBookInfo(Cursor mCursor, int idx) {
        BookInfo bookInfo = new BookInfo();
        String _id = null;
        String press = null;
        String grade = null;
        String reactOS = null;
        if (mCursor != null){
            try {
                _id = "" + idx;
                press = mCursor.getString(mCursor
                        .getColumnIndex(MHDataTable.PRESS));
                grade = mCursor.getString(mCursor
                        .getColumnIndex(MHDataTable.GRADE_NAME));
                reactOS = mCursor.getString(mCursor
                        .getColumnIndex(MHDataTable.REACTOS));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        bookInfo.set_id(_id);
        bookInfo.setPress(press);
        bookInfo.setGrade(grade);
        bookInfo.setReactOS(reactOS);
        return bookInfo;
    }

    public static List<String> getTableTypes(String press, String grade_name, String reactOS ){

        SQLiteDatabase mDB = null;
        List<String> mList = new ArrayList<String>();
        Cursor mCursor = null;

        mDB = SQLiteDatabase.openDatabase(Constants.MH_DATABASE_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        mCursor = mDB.rawQuery("select DISTINCT " + MHDataTable.TABLE_TYPE + " from " + MHDataTable.DATA_WORD_TABLE_NAME
                + " WHERE "+ MHDataTable.PRESS + " = ? and " + MHDataTable.GRADE_NAME + " = ? and " + MHDataTable.REACTOS + " = ?",
                new String[] { press, grade_name, reactOS});
        if (mCursor != null) {
            while (mCursor.moveToNext()) {
                String type = mCursor.getString(mCursor
                        .getColumnIndex(MHDataTable.TABLE_TYPE));
                mList.add(type);
            }
            mCursor.close();
        }

        mDB.close();
        return mList;
    }

    public static List<TitleWord> getTitleWords(String press, String grade_name, String reactOS, String table_type ){

        SQLiteDatabase mDB = null;
        List<TitleWord> mList = new ArrayList<TitleWord>();
        Cursor mCursor = null;

        mDB = SQLiteDatabase.openDatabase(Constants.MH_DATABASE_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        mCursor = mDB.rawQuery("select DISTINCT " + MHDataTable.SERIAL_NUMBER + ", " + MHDataTable.TITLE
                        + " from " + MHDataTable.DATA_WORD_TABLE_NAME + " WHERE "+ MHDataTable.PRESS + " = ? and "
                        + MHDataTable.GRADE_NAME + " = ? and " + MHDataTable.REACTOS + " = ? and "
                        + MHDataTable.TABLE_TYPE + " = ?",
                new String[] { press, grade_name, reactOS, table_type});

        if (mCursor != null) {
            while (mCursor.moveToNext()) {
                String serial_number = mCursor.getString(mCursor
                        .getColumnIndex(MHDataTable.SERIAL_NUMBER));
                String title = mCursor.getString(mCursor
                        .getColumnIndex(MHDataTable.TITLE));
                TitleWord titleWord = new TitleWord();
                titleWord.setSerialNumber(serial_number);
                titleWord.setTitle(title);
                mList.add(titleWord);
            }
            mCursor.close();
        }

        mDB.close();
        return mList;
    }

    public static List<RowWord> getRowWords(BookInfo book, String table_type, TitleWord titleWord){

        SQLiteDatabase mDB = null;
        List<RowWord> mList = new ArrayList<RowWord>();
        Cursor mCursor = null;

        mDB = SQLiteDatabase.openDatabase(Constants.MH_DATABASE_PATH, null,
                SQLiteDatabase.OPEN_READONLY);
        mCursor = mDB.rawQuery("select DISTINCT " + MHDataTable.ORDER_NUMBER + ", " + MHDataTable.NEW_WORD
                        + " from " + MHDataTable.DATA_WORD_TABLE_NAME + " WHERE "+ MHDataTable.PRESS + " = ? and "
                        + MHDataTable.GRADE_NAME + " = ? and " + MHDataTable.REACTOS + " = ? and "
                        + MHDataTable.TABLE_TYPE + " = ? and " + MHDataTable.SERIAL_NUMBER + " = ? and "
                        + MHDataTable.TITLE + " = ?",
                new String[] { book.getPress(), book.getGrade(), book.getReactOS(), table_type,
                        titleWord.getSerialNumber(), titleWord.getTitle()});

        if (mCursor != null) {
            while (mCursor.moveToNext()) {
                String order_number = mCursor.getString(mCursor
                        .getColumnIndex(MHDataTable.ORDER_NUMBER));
                String row_word = mCursor.getString(mCursor
                        .getColumnIndex(MHDataTable.NEW_WORD));
                RowWord rowWord = new RowWord();
                rowWord.setOrderNum(order_number);
                rowWord.setRowStr(row_word);
                mList.add(rowWord);
            }
            mCursor.close();
        }

        mDB.close();
        return mList;
    }


    public static void  initDB(final Context context, final InitCallback callback){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String databaseFilename = Constants.MH_DATABASE_DIR_PATH + "/mh.db";
                File dir = new File(Constants.MH_DATABASE_DIR_PATH);
                if (!dir.exists())
                    dir.mkdir();
                if (!(new File(databaseFilename)).exists()) {
                    try {
//                InputStream is = context.getResources().openRawResource(R.raw.address);
                        InputStream is = context.getResources().getAssets().open("mh.db");
                        FileOutputStream fos = new FileOutputStream(databaseFilename);
                        byte[] buffer = new byte[2048];
                        int i = 0;
                        while ((i = is.read(buffer)) > 0) {
                            fos.write(buffer, 0, i);
                        }
                        fos.flush();
                        fos.close();
                        is.close();
                    } catch (IOException e) {
                        new File(databaseFilename).delete();
                        callback.onError(e);
                        return;
                    }
                }
                callback.onSucess();
            }
        }).run();
    }
}
