package kz.arta.synergy.workflow.mobile.android.works.activities.completion;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.devspark.appmsg.AppMsg;
import com.google.gson.JsonSyntaxException;
import com.pnikosis.materialishprogress.ProgressWheel;

import kz.arta.synergy.workflow.mobile.android.R;
import kz.arta.synergy.workflow.mobile.android.common.ActivityConst;
import kz.arta.synergy.workflow.mobile.android.common.SettingsConst;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.offline.add.AddResultWork;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.WorkActionsTable;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.WorkResultTable;
import kz.arta.synergy.workflow.mobile.android.common.requests.RestClient;
import kz.arta.synergy.workflow.mobile.android.common.requests.SendGetRequest;
import kz.arta.synergy.workflow.mobile.android.common.utils.ActionUtils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Fonts;
import kz.arta.synergy.workflow.mobile.android.common.utils.ImageLoader;
import kz.arta.synergy.workflow.mobile.android.common.utils.MyApplication;
import kz.arta.synergy.workflow.mobile.android.common.utils.Utils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Wrapper;
import kz.arta.synergy.workflow.mobile.android.files.manager.DownloadFile;
import kz.arta.synergy.workflow.mobile.android.forms.general.activities.FormPlayer;
import kz.arta.synergy.workflow.mobile.android.works.models.CompletionResultItem;
import kz.arta.synergy.workflow.mobile.android.works.models.CompletionWorkItem;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkItem;

/**
 * Created by neox on 12.05.14.
 * Результат работы
 */
public class ResultWorkActivity extends Activity {

    /**
     * Для открытия активти "Отклонить"
     */
    private static final int REJECT = 1;

    /**
     * Прогресс бар
     */
    private ProgressWheel progressBar;

    /**
     * Активити
     */
    private Activity activity;

    /**
     * Данные для авторизированного пользователя
     */
    private Person person;

    /**
     * Объект "Работа"
     */
    private WorkItem work;

    /**
     * id результата завершения
     */
    private String resultID;

    /**
     * Настройки
     */
    private SharedPreferences settings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.result_work_activity);

        activity = this;

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
            ((TextView) findViewById(R.id.title_action_bar_result)).setTypeface(Fonts.getMedium(activity));
        }

        Intent intent = getIntent();
        person = (Person) intent.getSerializableExtra(ActivityConst.PERSON);
        work = (WorkItem) intent.getSerializableExtra(ActivityConst.WORK);

        settings = activity.getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE);

        progressBar = (ProgressWheel) findViewById(R.id.result_work_progress_bar);

        Button accept = (Button) findViewById(R.id.button_agree);
        accept.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Utils.isOnline(activity, person.getHost())) {
                    new AcceptWorkResult().execute();
                } else if (Utils.checkSyncEnables(settings)) {
                    // подтверждение работы
                    AddResultWork addResultWork = new AddResultWork(activity);
                    addResultWork.accept(work.getActionID(), resultID, "accept", work.getName());
                    // удаление кнопок
                    WorkActionsTable actions = new WorkActionsTable(activity);
                    actions.removeByActionID(work.getActionID());
                    // intent
                    Intent intent = new Intent();
                    intent.putExtra(ActivityConst.ACCEPT, work);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });

        Button reject = (Button) findViewById(R.id.button_not_agree);
        reject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(activity, RejectWorkActivity.class);
                intent.putExtra(ActivityConst.PERSON, person);
                intent.putExtra(ActivityConst.WORK_ID, work.getActionID());
                intent.putExtra(ActivityConst.START_DATE, work.getStart_date());
                intent.putExtra(ActivityConst.FINISH_DATE, work.getFinish_date());
                intent.putExtra(ActivityConst.PROGRESS_REJECT, work.getPercent());
                intent.putExtra(ActivityConst.RESULT_ID, resultID);
                intent.putExtra(ActivityConst.WORK_NAME, work.getName());
                startActivityForResult(intent, REJECT);
            }
        });

        new ShowBlock().execute();
    }

    /**
     * Леяут с результатом завершения работы для формы завершения файл
     *
     * @param result - леяут с результатом завершения
     */
    private void fileResult(final CompletionResultItem result) {

        LinearLayout resultBlock = (LinearLayout) findViewById(R.id.result_work_file_result_work_block);

        ImageView icon = (ImageView) resultBlock.findViewById(R.id.result_work_file_icon);
        ImageLoader imageLoader = new ImageLoader(activity, person);

        TextView attachName = (TextView) resultBlock.findViewById(R.id.result_work_file_text);
        attachName.setTypeface(Fonts.getMedium(activity));

        final String fileName;
        final String fileUUID = result.getFileUUID();
        final String dataUUID = result.getDataUUID();

        attachName.setText(result.getFile_name());
        fileName = result.getFile_name();
        imageLoader.displayImage(person.getHost() + result.getFile_icon(), icon);

        resultBlock.setVisibility(View.VISIBLE);
        resultBlock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (dataUUID != null) {
                    // todo здесь по идее надо проверять есть ли у формы мобильное представление..
                    Intent intent = new Intent(activity, FormPlayer.class);
                    intent.putExtra(ActivityConst.DATA_UUID, dataUUID);
                    intent.putExtra(ActivityConst.PERSON, person);
                    intent.putExtra(ActivityConst.CAN_EDIT, "true");
                    startActivityForResult(intent, ActionUtils.SAVE_FORM);
                } else {
                    DownloadFile downloadFile = new DownloadFile(activity, person);
                    downloadFile.setFileName(fileName);
                    downloadFile.setUrl(person.getHost() + "rest/api/storage/pdf/get?identifier=" + fileUUID);
                    downloadFile.execute();
                }
            }
        });
    }

    /**
     * Леяут с результатом завершения работы для формы завершения комментарий
     *
     * @param completionResultItem - леяут с результатом завершения
     */
    private void commentResult(CompletionResultItem completionResultItem) {
        RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.result_work_comment_result_work_block);

        TextView nameText = (TextView) findViewById(R.id.result_work_comment_name);
        nameText.setTypeface(Fonts.getMedium(activity));
        nameText.setText(completionResultItem.getUser_name());

        TextView commentText = (TextView) findViewById(R.id.result_work_comment_text);
        commentText.setTypeface(Fonts.getRoman(activity));
        commentText.setText(completionResultItem.getComment());

        TextView timeText = (TextView) findViewById(R.id.result_work_comment_time);
        timeText.setTypeface(Fonts.getMedium(activity));
        timeText.setText(completionResultItem.getCreated());

        relativeLayout.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_CANCELED && requestCode == REJECT) {
            if (Utils.isOnline(activity, person.getHost())) {
                WorkItem workItem = (WorkItem) data.getSerializableExtra(ActivityConst.WORK);
                Intent intent = new Intent();
                intent.putExtra(ActivityConst.WORK, workItem);
                activity.setResult(RESULT_OK, intent);
                activity.finish();
            } else if (Utils.checkSyncEnables(settings)) {
                work.setPercent(data.getStringExtra("progress"));
                Intent intent = new Intent();
                intent.putExtra(ActivityConst.REJECT_OFFLINE, work);
                intent.putExtra("comment", data.getStringExtra("comment"));
                activity.setResult(RESULT_OK, intent);
                activity.finish();
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    /**
     * Класс отвечает за загрузку и отображение блока "форма завершения работы"
     */
    class ShowBlock extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                CompletionResultItem completionResultItem;
                try {
                    completionResultItem = RestClient.getGson().fromJson(result, CompletionResultItem.class);
                } catch (JsonSyntaxException exc) {
                    completionResultItem = null;
                }
                if (completionResultItem != null) {
                    resultID = completionResultItem.getResultID();
                    if (completionResultItem.getType().equals(ActivityConst.COMMENT)) {
                        commentResult(completionResultItem);
                    }
                    if (completionResultItem.getType().equals(ActivityConst.FORM) || completionResultItem.getType().equals(ActivityConst.FILE)) {
                        fileResult(completionResultItem);
                    }
                }
                progressBar.setVisibility(View.GONE);
            }
            if (Utils.checkSyncEnables(settings)) {
                CompletionResultItem completionResultItem = new WorkResultTable(activity).get(work.getActionID());
                resultID = completionResultItem.getResultID();
                if (completionResultItem.getType().equals(ActivityConst.COMMENT)) {
                    commentResult(completionResultItem);
                }
                if (completionResultItem.getType().equals(ActivityConst.FORM) || completionResultItem.getType().equals(ActivityConst.FILE)) {
                    fileResult(completionResultItem);
                }
            }
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            return new SendGetRequest(person).requestGET(person.getHost() +
                    "rest/api/workflow/work/completion_result?workID=" + work.getActionID() + "&locale=" + MyApplication.getLang());
        }
    }

    /**
     * Отправляет запрос на подтверждение работы
     */
    class AcceptWorkResult extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            progressBar.setVisibility(View.VISIBLE);
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String result) {
            if (result != null) {
                CompletionWorkItem params = null;
                try {
                    params = RestClient.getGson().fromJson(result, CompletionWorkItem.class);
                } catch (Exception exc) {
                    AppMsg.makeText(activity, activity.getString(R.string.error_parsing), AppMsg.STYLE_ALERT).show();
                }
                if (params != null) {
                    if (params.getErrorCode().equals(Wrapper.NO_ERROR)) {
                        Intent intent = new Intent();
                        intent.putExtra(ActivityConst.WORK, params.getWork());
                        setResult(RESULT_OK, intent);
                        finish();

                    } else {
                        AppMsg.makeText(activity, result, AppMsg.STYLE_ALERT).show();
                    }
                }
            } else {
                AppMsg.makeText(activity, activity.getString(R.string.error_request), AppMsg.STYLE_ALERT).show();
            }
            progressBar.setVisibility(View.GONE);
            super.onPostExecute(result);
        }

        @Override
        protected String doInBackground(Void... voids) {
            return new SendGetRequest(person).requestGET(person.getHost() + "rest/api/workflow/work/accept_result?workID=" + work.getActionID()
                    + "&resultID=" + resultID + "&locale=" + MyApplication.getLang());
        }
    }
}
