package com.example.meteo;

import android.os.AsyncTask;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class FetchData extends AsyncTask<String,Void,LastMeasurement>
{
    public AsyncResponse delegate = null;//Call back interface
    private String dateTimeFormat = "yyyy-MM-dd'T'HH:mm:ss";

    /** AsyncResponse interface
     * Used to deliver result to activity and widget
     * */
    public interface AsyncResponse
    {
        void processFinish(LastMeasurement lastMeasurement);
    }

    /** LastMeasurement
     * Fetch and parse data in background task
     * */
    @Override
    protected LastMeasurement doInBackground(String... parameters)
    {
        String stringUrl = parameters[0];
        String result;
        //This format is used in .NET web application
        Gson gson = new GsonBuilder().setDateFormat(dateTimeFormat).create();
        LastMeasurement data = null;

        try
        {
            // Create url from string
            URL url = new URL(stringUrl);
            // Make connection to desired url
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);

            InputStream inputStream = new BufferedInputStream(connection.getInputStream());
            if(inputStream==null)
            {
                //return null when input stream is null (no data fetched);
                return null;
            }
            BufferedReader bufRead = new BufferedReader(new InputStreamReader(inputStream));
            String line;

            StringBuilder stringBuilder = new StringBuilder();
            while((line=bufRead.readLine())!=null)
            {
                stringBuilder.append(line+"\n");
            }
            result = stringBuilder.toString();

            // Parse received json to LastMeasurement class
            data = gson.fromJson(result, LastMeasurement.class);

            //return LastMeasurement with received data;
            return data;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    /* This is executed after doInBackground */
    /** LastMeasurement
     * This is executed after doInBackground
     * Invoke delegate with result
     * */
    @Override
    protected void onPostExecute(LastMeasurement s)
    {
        super.onPostExecute(s);
        delegate.processFinish(s);
    }
}/* End class FetchData*/