package com.pavle.patternswitch.db;


import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.pavle.patternswitch.activities.CreateActivity;
import com.pavle.patternswitch.objects.Interaction;
import com.pavle.patternswitch.objects.Pattern;
import com.pavle.patternswitch.objects.Trigger;

import java.util.ArrayList;
import java.util.List;

public class DBOperator extends AsyncTask{

    private Context mContext;
    ProgressDialog progress;

    public DBOperator(Context c){
        mContext = c;
        progress = ProgressDialog.show(mContext, "Loading",
                "Saving pattern...", true);
    }

    @Override
    protected Object doInBackground(Object[] params) {
        Pattern p = (Pattern) params[0];

        List<Trigger> triggerList = savePatternAndExtractList(p);
        List<Interaction> interactionList = saveTriggersAndExtractList(triggerList);
        saveInteractionsList(interactionList);
        return null;
    }

    private void saveInteractionsList(List<Interaction> interactionList) {
        for(Interaction i:interactionList) {
            DBHelperInteraction db = new DBHelperInteraction(mContext);
            db.setInteraction(i.getTriggerUUID(), i.getDeviceName(), i.getMethodFlags());
        }
    }

    private List<Interaction> saveTriggersAndExtractList(List<Trigger> triggerList) {
        List<Interaction> interactionList = new ArrayList<>();
        for(Trigger t:triggerList) {
            DBHelperTrigger db = new DBHelperTrigger(mContext);
            db.setTrigger(t.getUUID(),t.getPatternUUID(),t.getDistance(),t.getTriggerDeviceName(),t.getGoingTo());
            for(Interaction i:t.getInteractionList()){
                i.setTriggerUUID(t.getUUID()); //Set triggerUUID for all interactions
            }
            interactionList.addAll(t.getInteractionList());
        }
        return  interactionList;
    }

    private List<Trigger> savePatternAndExtractList(Pattern p) {
        DBHelperPattern db = new DBHelperPattern(mContext);
        db.setPattern(p.getUUID(),p.getName(),p.getDescription());

        List<Trigger> t = p.getTriggerList();
        for(Trigger x:t){
            x.setPatternUUID(p.getUUID()); //SET patternUUID for all triggers
        }
        return t;
    }

    @Override
    protected void onPostExecute(Object o) {
        progress.dismiss();
        CreateActivity a = (CreateActivity) mContext;
        a.onSavingDone();
    }
}
