package kz.arta.synergy.workflow.mobile.android.documents.resolution.manager;

import android.util.Base64;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

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

/**
 * Created by neox on 15.09.14.
 * Сохранение/подтвержедние резолюции
 */
public class SaveResolution {

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

    /**
     * Метод используется для сохранения/принятия резолюции
     *
     * @param data       данные о элементах резолюции
     * @param workID     идентификатор работы
     * @param documentID идентификатор документа
     * @param accept     принимается резолюция либо сохраняется
     * @param projectID  идентификатор проекта документа
     * @param controlled является ли контрольным
     * @return
     */
    public String saveResolution(String data, String workID, String documentID, boolean accept, String projectID, boolean controlled) {

        try {

            URL url = new URL(person.getHost() + "rest/api/docflow/doc/save_resolution");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Accept", "application/json; charset=utf-8");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Cache-Control", "no-cache");
            String basicAuth = "Basic " + new String(Base64.encode(person.getAuth().getBytes(), Base64.NO_WRAP));
            conn.setRequestProperty("Authorization", basicAuth);

            conn.setUseCaches(false);
            conn.setDoInput(true);
            conn.setDoOutput(true);

            DataOutputStream request = new DataOutputStream(conn.getOutputStream());

            request.writeBytes("data=" + URLEncoder.encode(data, "utf-8") + "&");
            if (workID != null) {
                request.writeBytes("workID=" + URLEncoder.encode(workID, "utf-8") + "&");
            } else {
                request.writeBytes("documentID=" + URLEncoder.encode(documentID, "utf-8") + "&");
            }
            request.writeBytes("controlled=" + URLEncoder.encode(String.valueOf(controlled), "utf-8") + "&");

            if (projectID != null) {
                request.writeBytes("projectID=" + URLEncoder.encode(projectID, "utf-8") + "&");
            }

            if (accept) {
                request.writeBytes("type=" + URLEncoder.encode("ACCEPT", "utf-8") + "&");
            } else {
                request.writeBytes("type=" + URLEncoder.encode("SAVE", "utf-8") + "&");
            }

            request.writeBytes("locale=" + URLEncoder.encode(MyApplication.getLang(), "utf-8"));
            request.flush();
            request.close();

            InputStream is = conn.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }

            rd.close();
            return response.toString();
        } catch (Exception e) {
            return null;
        }
    }

    public void setPerson(Person person) {
        this.person = person;
    }
}
