package kz.arta.synergy.workflow.mobile.android.forms.mobile.manager;

import android.util.Base64;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import kz.arta.synergy.workflow.mobile.android.common.models.Person;

/**
 * Created by neox on 01.07.15.
 * Сохранение данных по форме
 */
public class SaveFormData {

    /**
     * Пользователь
     */
    private Person person;

    /**
     * UUID формы
     */
    private String formID;

    /**
     * UUID данных по форме
     */
    private String dataUUID;

    /**
     * Данные по форме
     */
    private String data;

    public SaveFormData(Person person, String formID, String dataUUID, String data) {
        this.person = person;
        this.formID = formID;
        this.dataUUID = dataUUID;
        this.data = data;
    }

    /**
     * Метод сохраняет данные по форме
     *
     * @return - результат
     */
    public String saveForm(boolean mobile) {

        try {

            URL url = new URL(person.getHost() + "rest/api/asforms/data/save?formUUID=" + formID + "&uuid=" + dataUUID);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setAllowUserInteraction(false);
            conn.setRequestProperty("Accept", "application/json; charset=utf-8");

            String basicAuth = "Basic " + new String(Base64.encode(person.getAuth().getBytes(), Base64.NO_WRAP));
            conn.setRequestProperty("Authorization", basicAuth);

            OutputStream out = conn.getOutputStream();
            Writer writer = new OutputStreamWriter(out, "UTF-8");
            writer.write("data=" + URLEncoder.encode(data, "utf-8"));
            writer.close();
            out.close();

            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String output;
            StringBuilder result = new StringBuilder();

            while ((output = br.readLine()) != null) {
                result.append(output);
            }
            conn.disconnect();

            return result.toString();

        } catch (Exception e) {
            return null;
        }
    }
}
