package com.pavle.patternswitch.db;

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

import com.pavle.patternswitch.objects.Pattern;
import com.pavle.patternswitch.objects.Trigger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * Database helper that helps load resources from DB
 */
public class DBHelperPattern {

    private Context mContext;
    public String databasePath = "";
    public String databaseName = "patterns.sqlite";
    public SQLiteDatabase database=null;
    public File databaseFile;

    /**
     * @param context
     * @return
     */
    public DBHelperPattern(Context context) {
        // TODO Auto-generated constructor stub
        this.mContext = context;
        databasePath = "data/data/"+context.getPackageName()+"/"+databaseName;
        databaseFile = new File(databasePath);
        if(!databaseFile.exists())
            try {
                deployDataBase(databaseName, databasePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    /**
     *
     * copy database to devices
     * @param databaseName
     * @param tagertPath
     * @throws IOException
     */
    private void deployDataBase(String databaseName, String tagertPath) throws IOException    {
        InputStream myInput = mContext.getAssets().open(databaseName);
        String outFileName = tagertPath;
        OutputStream myOutput = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer))>0)
        {
            myOutput.write(buffer, 0, length);
        }

        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public int getNumberOfPatterns(){

        int count=0;
        String query="SELECT COUNT(Pattern.ID) From Pattern";
        Cursor cursor;

        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);

        try {
            cursor =  database.rawQuery(query, null);
            if (cursor != null){
                cursor.moveToFirst();
                int j = cursor.getInt(0);
                count = j;
            }

            if (cursor!=null) {
                cursor.close();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }finally{
            database.close();
        }


        return count;
    }

    public Pattern getPattern(int id){

        Pattern currentPattern = null;

        String query="SELECT * FROM Pattern WHERE Pattern.ID=";
        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);

        while (currentPattern==null) {

            query+=String.valueOf(id)+";";


            Cursor  cursor =  database.rawQuery(query, null);
            if (cursor==null || cursor.getCount()==0) {
                cursor.close();
                return null;
            }else{
                cursor.moveToFirst();
                do
                {
                    currentPattern = createPattern(cursor);

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



        return currentPattern;

    }

    private Pattern createPattern(Cursor cursor) {
        Pattern p;
        List<Trigger> triggerList = getTriggerList(cursor.getString(1));
        p = new Pattern(triggerList);
        p.setName(cursor.getString(2));
        p.setDescription(cursor.getString(3));
        p.setUUID(UUID.fromString(cursor.getString(1)));
        return  p;
    }

    private List<Trigger> getTriggerList(String uuid){
        DBHelperTrigger dbT = new DBHelperTrigger(mContext);
        return dbT.getTriggers(uuid);
    }

    public void setPattern(UUID uuid,String name,String description){
        String query="";
        query = "INSERT INTO Pattern (UUID,Name,Description) VALUES (";
        query+="'"+uuid.toString()+"', '"+name+"', '"+description+"'";
        query+=");";
        try {
            database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
            database.execSQL(query);
            database.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            database.close();
        }
    }
    public void deletePattern(int id) {
        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
        String query = "DELETE FROM Pattern WHERE ID="+String.valueOf(id);
        try{
            database.execSQL(query);
            database.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    public void deletePattern(UUID id) {
        String uid = id.toString();
        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
        String query = "DELETE FROM Pattern WHERE UUID='"+String.valueOf(uid)+"'";
        try{
            database.execSQL(query);
            database.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }

    public Pattern getPattern(UUID id) {

        Pattern currentPattern = null;

        String query = "SELECT * FROM Pattern WHERE Pattern.UUID=";
        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);

        while (currentPattern == null) {

            query += "'" + String.valueOf(id) + "';";


            Cursor cursor = database.rawQuery(query, null);
            if (cursor == null || cursor.getCount() == 0) {
                cursor.close();
                return null;
            } else {
                cursor.moveToFirst();
                do {
                    currentPattern = createPattern(cursor);

                } while (cursor.moveToNext());
                cursor.close();
            }
        }
        return currentPattern;
    }
}
