package kz.arta.synergy.workflow.mobile.android.documents.common.activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import com.devspark.appmsg.AppMsg;
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.AddChangeProgress;
import kz.arta.synergy.workflow.mobile.android.common.offline.get.WorksTable;
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.DateUtils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Fonts;
import kz.arta.synergy.workflow.mobile.android.common.utils.MyApplication;
import kz.arta.synergy.workflow.mobile.android.common.utils.StatusWork;
import kz.arta.synergy.workflow.mobile.android.common.utils.Utils;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkItem;

/**
 * Created by neox on 20.01.15.
 * Фрагмент в информации о документе (используется только в том случае, если у документа есть работы)
 */
public class FragmentDocumentInfoPager extends Fragment {

    /**
     * Прогрессбар
     */
    private static ProgressWheel progressBar;
    /**
     * Объект "Работа"
     */
    private WorkItem work;
    /**
     * Пользователь
     */
    private Person person;
    /**
     * Прогресс работы
     */
    private int workPercent;
    /**
     * Имя формы завершения
     */
    private String formCompletion;
    /**
     * UUID формы завершения (имеется только если форма завершения форма)
     */
    private String formID;
    /**
     * Прогресс работы
     */
    private SeekBar progressWorkSeekBar;

    public static FragmentDocumentInfoPager newInstance(WorkItem work, Person person, String formCompletion,
                                                        String formID, ProgressWheel progress) {
        FragmentDocumentInfoPager pageFragment = new FragmentDocumentInfoPager();
        Bundle arguments = new Bundle();
        arguments.putSerializable(ActivityConst.WORK, work);
        arguments.putSerializable(ActivityConst.PERSON, person);
        arguments.putSerializable(ActivityConst.FORM_COMPLETION, formCompletion);
        arguments.putSerializable(ActivityConst.FORM_ID, formID);
        pageFragment.setArguments(arguments);
        progressBar = progress;
        return pageFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        work = (WorkItem) getArguments().getSerializable(ActivityConst.WORK);
        person = (Person) getArguments().getSerializable(ActivityConst.PERSON);
        formCompletion = (String) getArguments().getSerializable(ActivityConst.FORM_COMPLETION);
        formID = (String) getArguments().getSerializable(ActivityConst.FORM_ID);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        workPercent = Integer.parseInt(work.getPercent());

        View view = inflater.inflate(R.layout.document_info_view_pager_item, null);

        TextView workName = (TextView) view.findViewById(R.id.work_info_work_name);
        workName.setText(work.getName());
        workName.setTypeface(Fonts.getRoman(getActivity()));

        if (work.getIs_expired().equals("true")) {
            workName.setTextColor(getActivity().getResources().getColor(R.color.expired_color_work));
        } else if (work.getIs_soon_expired().equals("true")) {
            workName.setTextColor(getActivity().getResources().getColor(R.color.soon_expired_color_work));
        } else {
            workName.setTextColor(getActivity().getResources().getColor(R.color.default_color_work));
        }

        TextView authorLabel = (TextView) view.findViewById(R.id.work_info_author_label);
        authorLabel.setTypeface(Fonts.getRoman(getActivity()));

        TextView author = (TextView) view.findViewById(R.id.work_info_author);
        author.setText(work.getAuthor().getName());
        author.setTypeface(Fonts.getMedium(getActivity()));

        if (work.getAuthor().getName() == null || work.getAuthor().getName().isEmpty()) {
            authorLabel.setVisibility(View.GONE);
            author.setVisibility(View.GONE);
        }

        TextView responsibleLabel = (TextView) view.findViewById(R.id.work_info_responsible_label);
        responsibleLabel.setTypeface(Fonts.getRoman(getActivity()));

        TextView responsible = (TextView) view.findViewById(R.id.work_info_responsible);
        responsible.setText(work.getUser().getName());
        responsible.setTypeface(Fonts.getMedium(getActivity()));

        if (work.getUser().getName() == null || work.getUser().getName().isEmpty()) {
            responsibleLabel.setVisibility(View.GONE);
            responsible.setVisibility(View.GONE);
        }

        TextView startDate = (TextView) view.findViewById(R.id.work_info_start_date);
        startDate.setText(DateUtils.parseDateWorkInfo(work.getStart_date(), getActivity()));
        startDate.setTypeface(Fonts.getRoman(getActivity()));

        TextView finishDate = (TextView) view.findViewById(R.id.work_info_finish_date);
        finishDate.setText(" - " + DateUtils.parseDateWorkInfo(work.getFinish_date(), getActivity()));
        finishDate.setTypeface(Fonts.getRoman(getActivity()));

        final TextView progressText = (TextView) view.findViewById(R.id.work_info_seek_bar_label);
        progressText.setText(work.getPercent() + "%");
        progressText.setTypeface(Fonts.getMedium(getActivity()));

        progressWorkSeekBar = (SeekBar) view.findViewById(R.id.work_info_seek_bar);
        progressWorkSeekBar.setProgress(Integer.parseInt(work.getPercent()));
        progressWorkSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                progressText.setText(seekBar.getProgress() + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                workPercent = seekBar.getProgress();
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (seekBar.getProgress() < 100) {
                    changeProgressDialog(getActivity());
                } else if (formCompletion != null && !formCompletion.equals("NOTHING")) {
                    progressBar.setVisibility(View.VISIBLE);
                    switch (formCompletion) {
                        case ActivityConst.FILE:
                            ActionUtils.openActivityCompletionWorkFile(getActivity(), person, work);
                            break;
                        case ActivityConst.COMMENT:
                            ActionUtils.openActivityCompletionWorkComment(getActivity(), person, work);
                            break;
                        case ActivityConst.FORM:
                            ActionUtils.openActivityCompletionWorkForm(getActivity(), person, work, formID, progressBar);
                            break;
                    }
                } else {
                    finishWorkDialog(getActivity());
                }
            }
        });

        if (!work.getCan_change_progress().equals("true")) {
            progressWorkSeekBar.setEnabled(false);
        }

        TextView statusWork = (TextView) view.findViewById(R.id.work_info_status);
        statusWork.setTypeface(Fonts.getMedium(getActivity()));

        StatusWork checkWork = new StatusWork();
        checkWork.setActivity(getActivity());
        checkWork.setSeekBar(progressWorkSeekBar);
        checkWork.setProgressText(progressText);
        checkWork.setStatusWork(statusWork);
        checkWork.checkStatus(work);

        return view;
    }

    /**
     * Диалог изменения прогресса
     */
    private void changeProgressDialog(Activity activity) {
        AlertDialog.Builder adb = new AlertDialog.Builder(activity);
        adb.setTitle(getString(R.string.change_progress_title));
        adb.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                changeProgress(progressWorkSeekBar.getProgress());
            }
        });
        adb.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                progressWorkSeekBar.setProgress(workPercent);
            }
        });
        adb.setMessage(getString(R.string.change_progress_answer));
        adb.show();
    }

    /**
     * Диалог завершения работы
     */
    public void finishWorkDialog(Activity activity) {
        AlertDialog.Builder adb = new AlertDialog.Builder(activity);
        adb.setTitle(getString(R.string.finish_work_title));
        adb.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                changeProgress(100);
            }
        });
        adb.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                progressWorkSeekBar.setProgress(workPercent);
            }
        });
        adb.setMessage(getString(R.string.finish_work_answer));
        adb.show();
    }

    /**
     * Метод отвечает за изменение прогресса работы
     * Если прогресс равен 100 - закрываем активити и обновляем список с работами
     */

    private void changeProgress(final int progress) {
        new SendGetRequest("rest/api/workflow/work/set_progress?workID=" + work.getActionID() +
                "&progress=" + progress + "&locale=" + MyApplication.getLang(), person) {
            @Override
            protected void onPreExecute() {
                progressBar.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String result) {
                progressBar.setVisibility(View.GONE);
                work.setPercent(String.valueOf(progress));
                if (result == null && Utils.checkSyncEnables(getActivity().getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE))) {
                    AddChangeProgress cProgress = new AddChangeProgress(getActivity());
                    cProgress.add(work.getActionID(), progress, work.getName());
                    new WorksTable(getActivity()).updateWork(work);
                } else if (result == null) {
                    AppMsg.makeText(getActivity(), getString(R.string.error_change_progress), AppMsg.STYLE_ALERT).show();
                }
//                if (progress == 100) {
//                    Intent intent = new Intent();
//                    intent.putExtra(ActivityConst.UPDATE_WORK_LIST, ActivityConst.UPDATE_WORK_LIST);
//                    getActivity().setResult(Activity.RESULT_OK, intent);
//                    getActivity().finish();
//                }
                super.onPostExecute(result);
            }
        }.execute();
    }
}
