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

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.devspark.appmsg.AppMsg;
import com.pnikosis.materialishprogress.ProgressWheel;

import java.util.List;

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.models.Person;
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.Utils;
import kz.arta.synergy.workflow.mobile.android.forms.general.activities.FormPlayer;
import kz.arta.synergy.workflow.mobile.android.works.manager.completion.CompletionWorkForm;
import kz.arta.synergy.workflow.mobile.android.works.models.ResultWorkItem;

/**
 * Created by neox on 12.04.16.
 * Завершение работы с формой завершения форма если есть перепорученные
 */
public class CompletionWorkFormActivity extends Activity {

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

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

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

    /**
     * Данные списка
     */
    private List<ResultWorkItem> data;

    /**
     * Идентификатор данных по форме
     */
    private String dataUUID;

    /**
     * Идентификатор результата завершения
     */
    private String resultID;

    /**
     * Идентификатор файла по форме
     */
    private String fileUUID;

    /**
     * Иденитфикатор текущей работы
     */
    private String workID;

    /**
     * Выделенный пункт
     */
    private int selectedItem = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        activity = this;

        data = (List<ResultWorkItem>) getIntent().getSerializableExtra(ActivityConst.PREVIOUS_RESULTS);
        person = (Person) getIntent().getSerializableExtra(ActivityConst.PERSON);
        workID = getIntent().getStringExtra(ActivityConst.WORK_ID);

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

        if (getActionBar() != null) {
            getActionBar().hide();
        }

        init();
    }

    /**
     * Инициализация
     */
    private void init() {
        // шапка списка
        data.add(0, new ResultWorkItem());
        final ArrayAdapter<ResultWorkItem> adapter = new FormsAdapter(data);
        ListView list = (ListView) findViewById(R.id.completion_work_form_list_view);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if (position == 0) {
                    return;
                }
                selectedItem = position;
                RelativeLayout layout = (RelativeLayout) findViewById(R.id.completion_work_form_result_block);
                layout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dataUUID = data.get(position).getDataUUID();
                        resultID = data.get(position).getResultID();
                        fileUUID = data.get(position).getFileUUID();
                        Intent intent = new Intent(activity, FormPlayer.class);
                        intent.putExtra(ActivityConst.DATA_UUID, dataUUID);
                        intent.putExtra(ActivityConst.PERSON, person);
                        intent.putExtra(ActivityConst.CAN_EDIT, "true");
                        startActivity(intent);
                    }
                });
                ImageView icon = (ImageView) findViewById(R.id.completion_work_form_result_icon);
                ImageLoader imageLoader = new ImageLoader(activity.getApplicationContext(), person);
                imageLoader.displayImage(Utils.parseUrlToIcon(person.getHost() + data.get(position).getFile_icon()), icon);
                TextView fileName = (TextView) layout.findViewById(R.id.completion_work_form_result_filename);
                fileName.setTypeface(Fonts.getMedium(activity));
                fileName.setText(data.get(position).getFile_name());
                layout.setVisibility(View.VISIBLE);
                adapter.notifyDataSetChanged();
            }
        });
        list.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        Button finish = (Button) findViewById(R.id.completion_work_form_button);
        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedItem == -1) {
                    AppMsg.makeText(activity, "Не выбран результат завершения", AppMsg.STYLE_ALERT).show();
                    return;
                }
                CompletionWorkForm completionWorkForm = new CompletionWorkForm();
                completionWorkForm.setActivity(activity);
                completionWorkForm.setPerson(person);
                completionWorkForm.setProgressBar(progressBar);
                completionWorkForm.setResultID(resultID);
                completionWorkForm.setFileIdentifier(fileUUID);
                completionWorkForm.setWorkID(workID);
                completionWorkForm.execute();
            }
        });
    }

    public class FormsAdapter extends ArrayAdapter<ResultWorkItem> {

        /**
         * Список завершенных работ
         */
        private List<ResultWorkItem> list;

        /**
         * Класс используется для получения из содержимого xml файла view
         */
        private LayoutInflater inflater;

        /**
         * Класс для асинхронной загрузки изображений
         */
        private ImageLoader imageLoader;

        public FormsAdapter(List<ResultWorkItem> list) {
            super(activity, R.layout.users_chooser_activity, list);
            this.list = list;
            inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            imageLoader = new ImageLoader(activity.getApplicationContext(), person);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view;
            if (position != 0) {
                view = inflater.inflate(R.layout.item_attachment, null);
                TextView nameAttachment = (TextView) view.findViewById(R.id.text_attach);
                nameAttachment.setTypeface(Fonts.getMedium(activity));
                nameAttachment.setText(list.get(position).getFile_name());
                ImageView image = (ImageView) view.findViewById(R.id.image_attach);
                try {
                    imageLoader.displayImage(Utils.parseUrlToIcon(person.getHost() + list.get(position).getFile_icon()), image);
                } catch (Exception ignored) {
                }
                if (position == list.size() - 1) {
                    View separator = view.findViewById(R.id.separator_attachment_item);
                    separator.setVisibility(View.GONE);
                }
                if (position == selectedItem) {
                    view.setBackgroundResource(R.drawable.choice_selected);
                } else {
                    view.setBackgroundResource(R.drawable.choice_unselected);
                }
            } else {
                view = inflater.inflate(R.layout.completion_work_form_list_head, null);
                TextView title = (TextView) view.findViewById(R.id.completion_work_form_list_head_title);
                title.setTypeface(Fonts.getMedium(activity));
            }
            return view;
        }
    }
}
