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

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

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

import java.util.HashSet;

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.documents.common.models.DocumentItem;
import kz.arta.synergy.workflow.mobile.android.documents.route.RouteManager;
import kz.arta.synergy.workflow.mobile.android.documents.route.RouteUtils;
import kz.arta.synergy.workflow.mobile.android.documents.route.RoutesConst;
import kz.arta.synergy.workflow.mobile.android.documents.route.models.Route;
import kz.arta.synergy.workflow.mobile.android.documents.route.models.RouteItem;
import kz.arta.synergy.workflow.mobile.android.documents.route.models.RouteItemUser;
import kz.arta.synergy.workflow.mobile.android.documents.route.models.Routes;

/**
 * Created by neox on 24.07.15.
 * Активити со списком маршрутов
 */
public class RouteActivity extends Activity {

    /**
     * Подробная информация о пунктах
     */
    public static final int ROUTE_ITEMS = 1;

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

    /**
     * Текущее активити
     */
    private Activity activity;

    /**
     * Маршруты по данному реестру
     */
    private Routes routes;

    /**
     * Тип маршрута, с которым работаем в данный момент
     *
     * @see RoutesConst#BEFORE
     * @see RoutesConst#ACTION
     * @see RoutesConst#AFTER
     */
    private int routeType;

    /**
     * Документ, по которому идет работа
     */
    private DocumentItem document;

    /**
     * Компонент, отображающий имя формы
     */
    private EditText formName;

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

    /**
     * Тип события
     *
     * @see RoutesConst#ACTIVATE
     * @see RoutesConst#CHANGE
     */
    private String type;

    /**
     * Коды этапов
     */
    private HashSet<String> codes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        activity = this;

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

        Intent intent = getIntent();
        person = (Person) intent.getSerializableExtra(ActivityConst.PERSON);
        routes = (Routes) intent.getSerializableExtra(RoutesConst.ROUTES);
        document = (DocumentItem) intent.getSerializableExtra(ActivityConst.DOCUMENT);
        type = (String) intent.getSerializableExtra(RoutesConst.ROUTE_TYPE);

        codes = new HashSet<>();

        init();
        initButton();
    }

    /**
     * Инициализация
     */
    private void init() {

        if (document == null) {
            return;
        }

        // имя формы
        formName = (EditText) findViewById(R.id.route_text);
        formName.setText(document.getFormName());

        // заголовок к "Предварительные этапы"
        LinearLayout beforeTitleLayout = (LinearLayout) findViewById(R.id.before_title_layout);
        beforeTitleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                routeType = RoutesConst.BEFORE;
                openActivity(routeType);
            }
        });

        // предварительные этапы
        LinearLayout beforeLayout = (LinearLayout) findViewById(R.id.before_layout);
        beforeLayout.removeAllViews();

        // заголовок к "Действия"
        LinearLayout actionTitleLayout = (LinearLayout) findViewById(R.id.action_title_layout);
        actionTitleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                routeType = RoutesConst.ACTION;
                openActivity(routeType);
            }
        });

        // действия
        LinearLayout actionLayout = (LinearLayout) findViewById(R.id.action_layout);
        actionLayout.removeAllViews();

        // заголовок к "Последующие этапы"
        LinearLayout afterTitleLayout = (LinearLayout) findViewById(R.id.after_title_layout);
        afterTitleLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                routeType = RoutesConst.AFTER;
                openActivity(routeType);
            }
        });

        // последующие этапы
        LinearLayout afterLayout = (LinearLayout) findViewById(R.id.after_layout);
        afterLayout.removeAllViews();

        if (routes.getBefore().getShowOnSave().equals("true")) {
            beforeTitleLayout.findViewById(R.id.before_title_layout).setVisibility(View.VISIBLE);
            beforeLayout.setVisibility(View.VISIBLE);
            initRoute(beforeLayout, routes.getBefore());
            beforeLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    routeType = RoutesConst.BEFORE;
                    openActivity(routeType);
                }
            });
        }

        if (routes.getAction().getShowOnSave().equals("true")) {
            actionTitleLayout.findViewById(R.id.action_title_layout).setVisibility(View.VISIBLE);
            actionLayout.setVisibility(View.VISIBLE);
            initRoute(actionLayout, routes.getAction());
            actionLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    routeType = RoutesConst.ACTION;
                    openActivity(routeType);
                }
            });
        }

        if (routes.getAfter().getShowOnSave().equals("true")) {
            afterTitleLayout.findViewById(R.id.after_title_layout).setVisibility(View.VISIBLE);
            afterLayout.setVisibility(View.VISIBLE);
            initRoute(afterLayout, routes.getAfter());
            afterLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    routeType = RoutesConst.AFTER;
                    openActivity(routeType);
                }
            });
        }

        codes = RouteUtils.getCodes(routes);
        progressBar = (ProgressWheel) findViewById(R.id.routes_activity_progress_bar);
    }

    /**
     * Инициализация кнопки
     */
    private void initButton() {
        Button startRouteButton = (Button) findViewById(R.id.start_route_button);
        startRouteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (formName.getText().toString().isEmpty()) {
                    AppMsg.makeText(activity, getString(R.string.need_enter_document_name), AppMsg.STYLE_ALERT).show();
                    return;
                }
                document.setFormName(formName.getText().toString());
                RouteManager routeManager = new RouteManager(routes, document, person, activity, type);
                if (routeManager.isValid()) {
                    routeManager.startRoute(progressBar);
                }
            }
        });
    }

    /**
     * Метод открывает активити - детали текущего маршрута
     */
    private void openActivity(int type) {
        Intent intent = new Intent(activity, RouteItemsActivity.class);
        intent.putExtra(ActivityConst.PERSON, person);
        intent.putExtra(RoutesConst.CODES, codes);
        switch (type) {
            case RoutesConst.BEFORE: {
                intent.putExtra(RoutesConst.ROUTE, routes.getBefore());
                intent.putExtra(RoutesConst.ROUTE_TYPE, RoutesConst.BEFORE);
            }
            break;
            case RoutesConst.ACTION: {
                intent.putExtra(RoutesConst.ROUTE, routes.getAction());
                intent.putExtra(RoutesConst.ROUTE_TYPE, RoutesConst.ACTION);
            }
            break;
            case RoutesConst.AFTER: {
                intent.putExtra(RoutesConst.ROUTE, routes.getAfter());
                intent.putExtra(RoutesConst.ROUTE_TYPE, RoutesConst.AFTER);
            }
            break;
        }
        startActivityForResult(intent, ROUTE_ITEMS);
    }

    /**
     * Инициализция леяута маршрута
     *
     * @param layout контейнер, в котором находится маршрут
     * @param route  тип маршрута (предварительные этапы, действия, последующие этапы)
     */
    private void initRoute(LinearLayout layout, Route route) {
        LayoutInflater inflater = activity.getLayoutInflater();
        for (RouteItem routeItem : route.getItems()) {
            for (RouteItemUser routeItemUser : routeItem.getUsers()) {
                View v = RouteUtils.getItem(inflater, routeItemUser, layout, activity, person);
                if (v == null) {
                    return;
                }
                layout.addView(v);
            }
        }
        RouteUtils.removeLastSplit(layout);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_CANCELED) {
            return;
        }
        if (requestCode == ROUTE_ITEMS) {
            Route route = (Route) data.getSerializableExtra(RoutesConst.ROUTE);
            if (route == null) {
                return;
            }
            switch (routeType) {
                case RoutesConst.BEFORE: {
                    routes.setBefore(route);
                }
                break;
                case RoutesConst.ACTION: {
                    routes.setActions(route);
                }
                break;
                case RoutesConst.AFTER: {
                    routes.setAfter(route);
                }
                break;
            }
            init();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

}
