package com.application.tak.takapplication.data_access;

import android.content.Context;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * Created by azielinska on 26/11/2017.
 */

public class UpdateTaskReadByClient extends GetJSONData {

    private static final String URI = Config.SERVER_NAME+ "update_task_is_read.php";

    public UpdateTaskReadByClient(Context ctx)
    {
        super(ctx);
        showProgressDialog = false;
    }

    public void Update(Integer clientId, Integer isRead)
    {
        execute(new String[]{clientId.toString(),isRead.toString()});
    }

    @Override
    protected String doInBackground(String... params)
    {       String result = "";

        String creator_id = params[0];
        String client_notification_read=params[1];

        try {
            URL url=new URL(URI);
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            OutputStream os=httpURLConnection.getOutputStream();

            String data= URLEncoder.encode("creator_id","UTF-8")+"="+URLEncoder.encode(creator_id,"UTF-8")+"&"+
                    URLEncoder.encode("client_notification_read","UTF-8")+"="+URLEncoder.encode(client_notification_read,"UTF-8")+"&"+
                    URLEncoder.encode("application_id","UTF-8")+"="+URLEncoder.encode(Config.ApplicationId,"UTF-8");

            BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
            bufferedWriter.write(data);
            bufferedWriter.flush();

            int statusCode = httpURLConnection.getResponseCode();
            if (statusCode == 200)
            {

                BufferedReader reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null)
                    sb.append(line).append("\n");

                result = sb.toString();
                bufferedWriter.close();
            }


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
