package kz.arta.synergy.workflow.mobile.android.forms.general.components.users.navigator;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import kz.arta.synergy.workflow.mobile.android.R;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
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.Fonts;
import kz.arta.synergy.workflow.mobile.android.common.utils.FragmentConst;
import kz.arta.synergy.workflow.mobile.android.common.utils.Utils;
import kz.arta.synergy.workflow.mobile.android.files.FilesConst;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.users.UsersChooserConst;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.users.activity.DepartmentsChooserActivity;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.users.activity.PositionsChooserActivity;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.users.activity.UsersChooserActivity;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.users.model.DepartmentModel;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.users.model.GroupsModel;
import kz.arta.synergy.workflow.mobile.android.forms.general.components.users.model.UserModel;

/**
 * Created by neox on 17.03.16.
 * Элемент списка
 */
public class UsersChooserNavigatorItem extends LinearLayout {

    /**
     * Выделенный пункт
     */
    private static UsersChooserNavigatorItem selectedItem;
    /**
     * Активити
     */
    private Activity activity;
    /**
     * Данные пользователя
     */
    private Person person;
    /**
     * Имя текущей папки
     */
    private TextView elementName;
    /**
     * Иконка отображающая состояние ноды (свернута/развернута)
     */
    private ImageView icon;
    /**
     * Состояние текущей ноды (свернута/развернута)
     */
    private boolean state;
    /**
     * Тип текущего элемента
     */
    private int type;
    /**
     * Тип компонента
     */
    private int componentType;
    /**
     * Уровень вложенности текущего элемента
     */
    private int level;
    /**
     * Имя
     */
    private String name;
    /**
     * Скрывать ли иконку
     */
    private boolean hideIcon;
    /**
     * Идентификатор группы
     */
    private int groupID;
    /**
     * Идентификатор департамента
     */
    private String departmentID;
    /**
     * Родители текущей ноды
     */
    private List<UserModel> parents;

    /**
     * Конструктор
     *
     * @param activity активити
     */
    public UsersChooserNavigatorItem(Activity activity) {
        super(activity);
        this.activity = activity;
    }

    /**
     * Метод добавляет в список view
     */
    public void add() {

        setOrientation(LinearLayout.VERTICAL);
        setLayoutParams(new LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
        setBackgroundColor(getResources().getColor(R.color.background_color_filters));

        LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        RelativeLayout contentLayout = (RelativeLayout) layoutInflater.inflate(R.layout.filters_item, null);
        contentLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (componentType) {
                    case UsersChooserConst.USER_CHOOSER: {
                        ((UsersChooserActivity) activity).hideMenu();
                        break;
                    }
                    case UsersChooserConst.DEPARTMENT_CHOOSER: {
                        ((DepartmentsChooserActivity) activity).hideMenu();
                        break;
                    }
                    case UsersChooserConst.POSITIONS_CHOOSER: {
                        ((PositionsChooserActivity) activity).hideMenu();
                        break;
                    }
                }
                tapItem();
                setSelected();
            }
        });

        // имя текущей папки
        elementName = (TextView) contentLayout.findViewById(R.id.name_filter);
        elementName.setText(name);
        elementName.setTypeface(Fonts.getRoman(activity));
        elementName.setTextColor(getResources().getColor(R.color.not_selected_filter_item));

        // отступ слева
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        // максимальное количество уровней со смещением - 8
        params.setMargins(Utils.dpToPx(FilesConst.DP_MARGIN_LEFT, activity) * (level < FilesConst.OFFSET_LEVELS ? level : FilesConst.OFFSET_LEVELS), 0, 0, 0);
        elementName.setLayoutParams(params);

        // иконка
        icon = (ImageView) contentLayout.findViewById(R.id.icon_filter);
        icon.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (state) {
                    collapse();
                } else {
                    expand();
                }
            }
        });

        if (hideIcon) {
            icon.setVisibility(View.GONE);
        }

        addView(contentLayout);
    }

    /**
     * Нажатие на плашку в дереве
     */
    public void tapItem() {
        if (componentType == UsersChooserConst.USER_CHOOSER) {
            UsersChooserActivity parentActivity = (UsersChooserActivity) activity;
            parentActivity.initPath(parents);
            if (type == UsersChooserConst.GROUPS) {
                if (groupID == 0) {
                    parentActivity.getGroups("");
                } else {
                    parentActivity.getUsers("rest/api/userchooser/search_ext?startRecord=0&recordsCount=" +
                            FragmentConst.DEFAULT_COUNT_WORKS + "&showAll=true&groupID=" + groupID + "&showGroups=true", "", UsersChooserConst.GROUPS, true, false);
                }
            } else if (type == UsersChooserConst.DEPARTMENTS) {
                parentActivity.getUsers("rest/api/userchooser/search_ext?startRecord=0&recordsCount=" +
                        FragmentConst.DEFAULT_COUNT_WORKS + "&showAll=true&departmentID=" + departmentID, "", UsersChooserConst.DEPARTMENTS, true, false);
            } else if (type == UsersChooserConst.OFTEN_USERS) {
                parentActivity.getUsers("rest/api/userchooser/getOftenChosenUsers?startRecord=0&recordsCount=" +
                        FragmentConst.DEFAULT_COUNT_WORKS + "&showAll=true", "", UsersChooserConst.OFTEN_USERS, true, false);
            } else if (type == UsersChooserConst.SELECTED_USERS) {
                parentActivity.getSelected();
            }
        } else if (componentType == UsersChooserConst.DEPARTMENT_CHOOSER) {
            DepartmentsChooserActivity parentActivity = (DepartmentsChooserActivity) activity;
            if (type == UsersChooserConst.SELECTED_USERS) {
                parentActivity.getSelected();
            } else if (type == UsersChooserConst.DEPARTMENTS) {
                parentActivity.getDepartments(departmentID, "", true);
            }
            parentActivity.initPath(parents);
        } else if (componentType == UsersChooserConst.POSITIONS_CHOOSER) {
            PositionsChooserActivity parentActivity = (PositionsChooserActivity) activity;
            if (type == UsersChooserConst.SELECTED_USERS) {
                parentActivity.getSelected();
            } else if (type == UsersChooserConst.DEPARTMENTS) {
                parentActivity.getPositions(departmentID, "", true);
            }
            parentActivity.initPath(parents);
        }
    }

    /**
     * Метод окрашивает цвет текста текущего элемента
     */
    public void setSelected() {
        if (selectedItem != null) {
            selectedItem.elementName.setTextColor(Color.LTGRAY);
        }
        selectedItem = UsersChooserNavigatorItem.this;
        elementName.setTextColor(getResources().getColor(R.color.selected_filter_item));
    }

    /**
     * Сворачивание текущей ноды
     */
    public void collapse() {
        level--;
        for (int i = getChildCount() - 1; i >= 1; i--) {
            removeViewAt(i);
        }
        state = false;
        icon.setImageResource(R.drawable.filters_undetailed);
        setSelected();
        tapItem();
    }

    /**
     * Раскрытие текущей ноды
     */
    public void expand() {
        level++;
        state = true;
        icon.setImageResource(R.drawable.filters_detailed);
        if (type == UsersChooserConst.GROUPS) {
            getGroups();
        } else {
            getDepartments();
        }
    }

    /**
     * Метод загружает группы
     */
    public void getGroups() {
        new SendGetRequest("rest/api/groups/content?loadAutoGroups=true&parentGroupID=" + groupID, person) {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    return;
                }
                try {
                    GroupsModel groupsModel = RestClient.getGson().fromJson(result, GroupsModel.class);
                    for (int i = 0; i < groupsModel.getArray().length; i++) {

                        UserModel userModel = new UserModel();
                        userModel.setDepartmentName(groupsModel.getArray()[i].name);

                        userModel.setUuid(String.valueOf(groupsModel.getArray()[i].groupID));
                        List<UserModel> parentNodes = new ArrayList<>();
                        for (UserModel user : parents) {
                            parentNodes.add(user);
                        }
                        parentNodes.add(userModel);

                        UsersChooserNavigatorItem item = new UsersChooserNavigatorItem(activity);
                        item.setPerson(person);
                        item.setName(groupsModel.getArray()[i].name);
                        item.setLevel(level + 1);
                        item.setGroupID(groupsModel.getArray()[i].groupID);
                        item.setType(UsersChooserConst.GROUPS);
                        item.setComponentType(componentType);
                        item.setParents(parentNodes);
                        item.setActivity(activity);
                        item.setHideIcon(!(groupsModel.getArray()[i].innerGroupsCount > 0));
                        item.add();

                        addView(item);
                    }
                } catch (Exception exc) {
                    // handling error...
                }
            }
        }.execute();
    }

    /**
     * Метод загружает департаменты
     */
    public void getDepartments() {
        new SendGetRequest("rest/api/userchooser/search_dept?departmentID=" + departmentID + "&showChildDepartments=false", person) {
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    return;
                }
                try {
                    DepartmentModel[] departments = RestClient.getGson().fromJson(result, DepartmentModel[].class);
                    for (DepartmentModel department : departments) {

                        UserModel userModel = new UserModel();
                        userModel.setDepartmentName(department.getDepartmentName());
                        userModel.setUuid(department.getDepartmentID());

                        List<UserModel> parentNodes = new ArrayList<>();
                        for (UserModel user : parents) {
                            parentNodes.add(user);
                        }
                        parentNodes.add(userModel);

                        UsersChooserNavigatorItem item = new UsersChooserNavigatorItem(activity);
                        item.setPerson(person);
                        item.setName(department.getDepartmentName());
                        item.setDepartmentID(department.getDepartmentID());
                        item.setLevel(level);
                        item.setType(UsersChooserConst.DEPARTMENTS);
                        item.setComponentType(componentType);
                        item.setParents(parentNodes);
                        item.setHideIcon(!department.isHasChildren());
                        item.setActivity(activity);
                        item.add();

                        addView(item);
                    }
                } catch (Exception exc) {
                    // handling error...
                }
            }
        }.execute();
    }

    public void setActivity(Activity activity) {
        this.activity = activity;
    }

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

    public void setLevel(int level) {
        this.level = level;
    }

    public void setHideIcon(boolean hideIcon) {
        this.hideIcon = hideIcon;
    }

    public void setParents(List<UserModel> parents) {
        this.parents = parents;
    }

    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    public String getDepartmentID() {
        return departmentID;
    }

    public void setDepartmentID(String departmentID) {
        this.departmentID = departmentID;
    }

    public int getGroupID() {
        return groupID;
    }

    public void setGroupID(int groupID) {
        this.groupID = groupID;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getComponentType() {
        return componentType;
    }

    public void setComponentType(int componentType) {
        this.componentType = componentType;
    }
}
