package torin.dmitry.fruitslots.game;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.AsyncTask;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import torin.dmitry.fruitslots.framework.ISettings;
import torin.dmitry.fruitslots.helpers.Mate;
import torin.dmitry.fruitslots.helpers.ScoreDBHelper;

/**
 * Created by Torin Dmitry on 30.05.2017.
 */
// должен быть публичным полем в Game
public class Settings implements ISettings {
    public static final float SOUND_MENU_VOL = 0.3f;
    public static final float SOUND_GAME_VOL = 0.3f;
    public static final float MUSIC_VOL = 0.3f;
    private final String tag = getClass().getSimpleName() + " -> ";
    private final String SOUND_TAG = "snd";
    private final String MUSIC_TAG = "msc";
    public static boolean soundEnable;
    public static boolean musicEnable;

    public static String[] highscoreStr = new String[]{":-)", ":-/", ":-(", ":->", "(:", "(:)", "=)", ":("};
    public static long[] highscoreLng = new long[highscoreStr.length];
    public static String[] dateOfScore = new String[highscoreStr.length];

    private Context context;
    private Calendar calendar = Calendar.getInstance();

    private SharedPreferences.Editor editor;
    private SharedPreferences settings;

    public Settings(Context c, SharedPreferences sp) {
        this.context = c;
        settings = sp;
        loadSettings();
    }

    @Override
    public void loadScores() {
        new ScoresLoader().execute();
    }

    @Override
    public void saveSettings() {
        editor = settings.edit();
        editor.putBoolean(SOUND_TAG, soundEnable);
        editor.putBoolean(MUSIC_TAG, musicEnable);
        editor.commit();
    }

    @Override
    public void loadSettings() {
        soundEnable = settings.getBoolean(SOUND_TAG, true);
        musicEnable = settings.getBoolean(MUSIC_TAG, true);
    }

    @Override
    public void addNewScore(long score) {
        if (score > highscoreLng[highscoreLng.length - 1]) {
            new AddNewScoreWorker(score).execute();
        }
    }

    private class ScoresLoader extends AsyncTask<Void, Void, Void> {
        private Cursor cursor;
        private SQLiteDatabase db;
        private SQLiteOpenHelper openHelper;

        @Override
        public Void doInBackground(Void...v) {
            try {
                openHelper = new ScoreDBHelper(context);
                db = openHelper.getReadableDatabase();
                cursor = db.query(
                        "SCORE",
                        new String[]{"_id", "VALUE", "DATE"},
                        null, null, null, null,
                        "VALUE DESC"
                );
            } catch (SQLiteException ex) {
                Mate.log("Ошибка при чтении БД с таблицей лучшего счета");
                Mate.log(ex.getMessage());
                ex.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            if (cursor.moveToFirst()) {
                ArrayList<Long> arrScore = new ArrayList<>();
                ArrayList<Long> arrDate = new ArrayList<>();
                arrScore.add(cursor.getLong(1));
                arrDate.add(cursor.getLong(2));
                while (cursor.moveToNext()) {
                    arrScore.add(cursor.getLong(1));
                    arrDate.add(cursor.getLong(2));
                }

                for (int i = 0; i < highscoreStr.length; i++) {
                    highscoreStr[i] = (i + 1) + ".    " + String.format(Locale.getDefault(), "%,d%n",arrScore.get(i)).trim().replace(',', ' ');
                    highscoreLng[i] = arrScore.get(i);
                    dateOfScore[i] = new SimpleDateFormat(
                            "dd/MM/yyyy", Locale.getDefault())
                            .format(new Date(arrDate.get(i))
                    );
                }

                cursor.close();
                db.close();

            }
        }
    }

    private class AddNewScoreWorker extends AsyncTask<Void, Void, Void> {
        private long addedValue;
        private Cursor cursor;
        private SQLiteDatabase db;
        private SQLiteOpenHelper openHelper;

        AddNewScoreWorker(long v) {
            this.addedValue = v;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                openHelper = new ScoreDBHelper(context);
                db = openHelper.getWritableDatabase();
                ContentValues cv = new ContentValues();
                cv.put("VALUE", addedValue);
                cv.put("DATE", calendar.getTimeInMillis());
                db.insert("SCORE", null, cv);
            } catch (SQLiteException ex) {
                Mate.log("Что-то не так при добавлении записи в базу лучшего счета...");
                Mate.log(ex.getMessage());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            loadScores();
        }
    }
}
