package com.pavle.patternswitch.db;

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

import com.pavle.patternswitch.objects.Device;
import com.pavle.patternswitch.objects.Interaction;
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.List;
import java.util.UUID;

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

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

    /**
     * @param context
     * @return
     */
    public DBHelperInteraction(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 getNumberOfInteractions(){

        int count=0;
        String query="SELECT COUNT(Interaction.ID) From Interaction";
        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 List<Interaction> getInteractions(String uuid){

        List<Interaction> list = new ArrayList<>();
        boolean FLAG_DONE = false;

        String query="SELECT * FROM Interaction WHERE Interaction.TriggerUUID=";
        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
        query+="'"+String.valueOf(uuid)+"';";

        while (!FLAG_DONE) {
            Cursor  cursor =  database.rawQuery(query, null);
            if (cursor==null || cursor.getCount()==0) {
                cursor.close();
                return null;
            }else{
                cursor.moveToFirst();
                do
                {
                    Interaction tmp  = createInteraction(cursor);
                    if(tmp!=null){
                        list.add(tmp);
                    }

                }while (cursor.moveToNext());
                cursor.close();
                FLAG_DONE = true;
            }
        }
        return list;

    }

    private Interaction createInteraction(Cursor cursor) {
        Interaction t;
        int methodFlags = cursor.getInt(2);
        t = new Interaction(null,methodFlags);
        t.setDeviceName(cursor.getString(1));
        return  t;
    }

    public void setInteraction(UUID triggerUUID,String deviceName,int methodFlags){
        String query="";
        query = "INSERT INTO Interaction (TriggerUUID,DeviceName,MethodFlags) VALUES (";
        query+="'"+triggerUUID.toString()+"', "+"'"+deviceName+"', "+String.valueOf(methodFlags);
        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 deleteInteraction(int id) {
        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
        String query = "DELETE FROM Interaction WHERE ID="+String.valueOf(id);
        try{
            database.execSQL(query);
            database.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    public void deleteInteractions(UUID triggerUUID) {
        String uid = triggerUUID.toString();
        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
        String query = "DELETE FROM Interaction WHERE TriggerUUID='"+String.valueOf(uid)+"'";
        try{
            database.execSQL(query);
            database.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
