package com.pavle.patternswitch.db;

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

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 DBHelperTrigger {

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

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

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

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

        String query="SELECT * FROM Trigger WHERE Trigger.PatternUUID=";
        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
                {
                    Trigger tmp  = createTrigger(cursor);
                    if(tmp!=null){
                        list.add(tmp);
                    }
                }while (cursor.moveToNext());
                cursor.close();
                FLAG_DONE = true;
            }
        }
        return list;

    }

    private Trigger createTrigger(Cursor cursor) {
        Trigger t;
        List<Interaction> interactionList = getInteractionList(cursor.getString(1));
        t = new Trigger(cursor.getInt(3),interactionList,cursor.getString(2));
        t.setUUID(UUID.fromString(cursor.getString(1)));
        t.setGoingTo(cursor.getInt(4));
        return  t;
    }



    private List<Interaction> getInteractionList(String uuid){
        DBHelperInteraction dbI = new DBHelperInteraction(mContext);
        return dbI.getInteractions(uuid);
    }

    public void setTrigger(UUID uuid,UUID patternUUID,int distance,String triggerDeviceName,int goingTo){
        String query="";
        query = "INSERT INTO Trigger (UUID,PatternUUID,Distance,TriggerDeviceName,GoingTo) VALUES (";
        query+="'"+uuid.toString()+"', "+"'"+patternUUID.toString()+"', "+""+String.valueOf(distance)
                +",'"+triggerDeviceName+"', '"+String.valueOf(goingTo)+"'";
        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 deleteTrigger(int id) {
        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
        String query = "DELETE FROM Trigger WHERE ID="+String.valueOf(id);
        try{
            database.execSQL(query);
            database.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
    public void deleteTrigger(UUID id) {
        String uid = id.toString();
        database = SQLiteDatabase.openDatabase(databasePath, null, SQLiteDatabase.OPEN_READWRITE);
        String query = "DELETE FROM Trigger WHERE UUID='"+String.valueOf(uid)+"'";
        try{
            database.execSQL(query);
            database.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}
