package kz.arta.synergy.workflow.mobile.android.files.layouts;

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 com.devspark.appmsg.AppMsg;
import com.pnikosis.materialishprogress.ProgressWheel;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import kz.arta.synergy.workflow.mobile.android.R;
import kz.arta.synergy.workflow.mobile.android.common.activities.MainActivity;
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.MyApplication;
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.files.fragments.FragmentFilesList;
import kz.arta.synergy.workflow.mobile.android.files.fragments.FragmentFilesTree;
import kz.arta.synergy.workflow.mobile.android.files.models.Node;
import kz.arta.synergy.workflow.mobile.android.files.offline.FilesFiltersTable;

/**
 * Created by neox on 01.10.15.
 * Дерево папок
 */
public class FoldersTree extends LinearLayout {

    /**
     * Фрагмент со списком файлов
     */
    private FragmentFilesList fragmentList;

    /**
     * Фрагмент с деревом папок
     */
    private FragmentFilesTree fragmentTree;

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

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

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

    /**
     * Имя текущей папки
     */
    private TextView elementName;

    /**
     * Иконка справа от имени
     */
    private ImageView icon;

    /**
     * Состояние (раскрыто/свернуто)
     */
    private boolean state;

    /**
     * Текущая нода
     */
    private Node node;

    /**
     * Родители текущей ноды
     */
    private List<Node> parents;

    /**
     * Уровень вложенности текущего элемента
     */
    private int level;

    /**
     * Конструктор
     *
     * @param text     имя папки
     * @param activity текущее активити
     * @param level    уровень вложенности
     */
    public FoldersTree(String text, final Activity activity, int level) {

        super(activity);

        this.activity = activity;
        this.level = level;

        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) {
                // выделение текущего элемента
                setSelected(true);
                // закрытие боковой навигации
                ((MainActivity) activity).getFiltersSlidingMenu().toggle();
            }
        });

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

        // hardcode..
        if (elementName.getText().equals("company_root")) {
            elementName.setText(getResources().getString(R.string.storage));
        }

        // отступ слева
        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 ItemClickListener());

        addView(contentLayout);
    }

    /**
     * Выделение текущей ноды
     */
    public void setSelected(boolean getFiles) {
        if (FragmentFilesTree.selectedItem != null) {
            FragmentFilesTree.selectedItem.elementName.setTextColor(Color.LTGRAY);
        }
        FragmentFilesTree.selectedItem = FoldersTree.this;
        elementName.setTextColor(getResources().getColor(R.color.selected_filter_item));
        // загрузка списка файлов
        if (getFiles) {
            fragmentList.getFiles(node, true, false);
        }
    }

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

    public void expand(List<Node> nodes) {
        level++;
        List<Node> parentNodes = new ArrayList<>();
        parentNodes.add(node);
        for (Node node : parents) {
            parentNodes.add(node);
        }
        for (Node currentNode : nodes) {
            FoldersTree foldersTree = new FoldersTree(currentNode.getName(), activity, level);
            foldersTree.setNode(currentNode);
            foldersTree.setProgressBar(progressBar);
            foldersTree.setPerson(person);
            foldersTree.setFragmentList(fragmentList);
            foldersTree.setFragmentTree(fragmentTree);
            foldersTree.setParents(parentNodes);
            addView(foldersTree);
        }
        state = true;
        icon.setImageResource(R.drawable.filters_detailed);
    }

    /**
     * Разворачивание текущей ноды
     */
    public void expand() {
        new SendGetRequest("rest/api/storage/list?parentID=" + node.getIdentifier() +
                "&getOnlyFolders=true&locale=" + MyApplication.getLang(), person) {
            @Override
            protected void onPreExecute() {
                progressBar.setVisibility(View.VISIBLE);
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(String result) {
                progressBar.setVisibility(View.GONE);
                if (result == null) {
                    result = new FilesFiltersTable(activity.getBaseContext()).get(person.getHost() + "rest/api/storage/list?parentID="
                            + node.getIdentifier() + "&getOnlyFolders=true&locale=" + MyApplication.getLang());
                }
                try {
                    Node[] files = RestClient.getGson().fromJson(result, Node[].class);
                    Arrays.sort(files, new Comparator<Node>() {
                        @Override
                        public int compare(Node node1, Node node2) {
                            return node1.getName().compareTo(node2.getName());
                        }
                    });
                    if (files.length == 0) {
                        icon.setVisibility(View.GONE);
                        return;
                    }
                    level++;
                    List<Node> parentNodes = new ArrayList<>();
                    parentNodes.add(node);
                    for (Node node : parents) {
                        parentNodes.add(node);
                    }
                    for (Node currentNode : files) {
                        FoldersTree foldersTree = new FoldersTree(currentNode.getName(), activity, level);
                        foldersTree.setNode(currentNode);
                        foldersTree.setProgressBar(progressBar);
                        foldersTree.setPerson(person);
                        foldersTree.setFragmentList(fragmentList);
                        foldersTree.setFragmentTree(fragmentTree);
                        foldersTree.setParents(parentNodes);
                        addView(foldersTree);
                    }
                } catch (Exception exc) {
                    AppMsg.makeText(activity, activity.getString(R.string.error_to_get_files), AppMsg.STYLE_ALERT).show();
                    return;
                }
                super.onPostExecute(result);
            }
        }.execute();
        state = true;
        icon.setImageResource(R.drawable.filters_detailed);
    }

    public void setFragmentTree(FragmentFilesTree fragmentTree) {
        this.fragmentTree = fragmentTree;
    }

    public List<Node> getParents() {
        return parents;
    }

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

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

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

    public void setProgressBar(ProgressWheel progressBar) {
        this.progressBar = progressBar;
    }

    public void setFragmentList(FragmentFilesList fragmentList) {
        this.fragmentList = fragmentList;
    }

    public TextView getElementName() {
        return elementName;
    }

    public Node getNode() {
        return node;
    }

    public void setNode(Node node) {
        this.node = node;
    }

    public boolean isState() {
        return state;
    }

    /**
     * Тап по изображению
     */
    private class ItemClickListener implements OnClickListener {
        public void onClick(View view) {
            if (state) {
                collapse(true);
            } else {
                expand();
            }
        }
    }
}