package cz.navtom.elektromer;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.TextView;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import static android.R.attr.name;

/**
 * Created by student on 21.3.2017.
 */

public class HttpReq extends AsyncTask {

    //intent filtry pro MainActivity
    public final static String HTTP_INFO_READY = "cz.navtom.elektromer.HTTP_INFO_READY";
    public final static String HTTP_SAVE_OK = "cz.navtom.elektromer.HTTP_SAVE_OK";
    public final static String HTTP_SAVE_ERR = "cz.navtom.elektromer.HTTP_SAVE_ERR";

    //pojmenovani requestu (pro action switch)
    public final static int HTTP_REQ_INFO = 1;
    public final static int HTTP_SAVE_DATA = 2;

    //objekt pro posilani do UI
    private Object toSend;

    //promenna pro pozadovanou operaci
    private int action;

    private final Context context;

    private boolean found       = true;
    private boolean dataSaved   = true;

    //konstruktor
    public HttpReq(Context context, int action) {

        this.context = context;
        this.action = action;

    }

    @Override
    protected Object doInBackground(Object[] params) {

        String baseUrl  = "http://navtom.cz/dp/api.php?";
        String info     = "";

        URL url;
        DocumentBuilderFactory dbf;
        DocumentBuilder db;
        Document doc;


        switch (action) {

            //Udaje zakaznika
            case HTTP_REQ_INFO:

                try {

                    //customer id
                    int cid = (int) params[0];

                    //sestaveni URL
                    url = new URL(baseUrl + String.format("q=c&cid=%d", cid));


                    dbf = DocumentBuilderFactory.newInstance();
                    db = dbf.newDocumentBuilder();

                    doc = db.parse(new InputSource(url.openStream()));
                    doc.getDocumentElement().normalize();

                    //Nod s infem o zakaznikovi
                    NodeList infoList = doc.getElementsByTagName("info");

                    //Ziskani retezce
                    info = infoList.item(0).getTextContent();

                    if (info == "") {
                        info = "Informace o zakaznikovi se nepodarilo ziskat";
                        found = false;
                    }


                } catch (Exception e) {
                    info = "Zákazník nenalezen";
                    found = false;
                    Log.d("Exception", e.toString());
                }

                toSend = info;

                break;

            //ulozeni dat do DB
            case HTTP_SAVE_DATA:



                try {

                    //data to save object
                    DataToSave data = (DataToSave) params[0];


                    //sestaveni URL
                    url = new URL(baseUrl + String.format("q=w&cid=%d&aid=%s&val=%d", data.cid, data.aid, data.aplus));

                    Log.d("URL", url.toString());

                    dbf = DocumentBuilderFactory.newInstance();
                    db = dbf.newDocumentBuilder();

                    doc = db.parse(new InputSource(url.openStream()));
                    doc.getDocumentElement().normalize();

                    //Nod s infem o zakaznikovi
                    NodeList bodyN = doc.getElementsByTagName("body");

                    //Ziskani retezce
                    info = bodyN.item(0).getTextContent();


                } catch (Exception e) {

                    dataSaved   = false;
                    Log.d("Exception", e.toString());

                }

                if (info.contains("ERR")) {

                    dataSaved   = false;

                }

                break;
        }
        return null;
    }

    @Override
    protected void onPostExecute(Object o) {

        Intent intent = null;

        switch (action) {

            case HTTP_REQ_INFO:

                intent = new Intent(HTTP_INFO_READY);
                intent.putExtra("info", (String) toSend);
                intent.putExtra("found", (boolean) found);

                break;

            case HTTP_SAVE_DATA:


                if (dataSaved) {

                    intent = new Intent(HTTP_SAVE_OK);

                }
                else {

                    intent = new Intent(HTTP_SAVE_ERR);

                }

                break;

        }

        context.sendBroadcast(intent);

    }
}
