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

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import kz.arta.synergy.workflow.mobile.android.R;
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.files.FilesConst;
import kz.arta.synergy.workflow.mobile.android.files.manager.SearchParams;

/**
 * Created by neox on 27.10.15.
 * Экран с параметрами для поиска файлов
 */
public class SearchParamsActivity extends Activity {

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

    /**
     * Параметры поиска
     */
    private SearchParams params;

    /**
     * Количество файлов при поиске для каждого из типа файлов
     */
    private List<Integer> fileTypesCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.files_search_params_activity);

        activity = this;

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

        Intent intent = getIntent();
        params = (SearchParams) intent.getSerializableExtra(FilesConst.SEARCH_PARAMS);
        fileTypesCount = (List<Integer>) intent.getSerializableExtra(FilesConst.FILES_TYPES_COUNT);

        init();
    }

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

        final TextView onCategory = (TextView) findViewById(R.id.files_search_params_category);
        onCategory.setTypeface(Fonts.getMedium(activity));
        onCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showCategoryDialog(onCategory);
            }
        });

        if (params.getAiType() == null) {
            onCategory.setText(getString(R.string.all_results));
        } else {
            switch (params.getAiType()) {
                case FilesConst.AI_DOCUMENT:
                    onCategory.setText(getString(R.string.documents));
                    break;
                case FilesConst.AI_IMAGE:
                    onCategory.setText(getString(R.string.images));
                    break;
                case FilesConst.AI_VIDEO:
                    onCategory.setText(getString(R.string.videos));
                    break;
                case FilesConst.AI_AUDIO:
                    onCategory.setText(getString(R.string.audios));
                    break;
                case FilesConst.AI_APPLICATION:
                    onCategory.setText(getString(R.string.some));
                    break;
            }
        }

        final TextView onDate = (TextView) findViewById(R.id.files_search_params_date);
        onDate.setTypeface(Fonts.getMedium(activity));
        onDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDateDialog(onDate);
            }
        });

        switch (params.getSortDate()) {
            case 0:
                onDate.setText(getString(R.string.in_all_time));
                break;
            case 1:
                onDate.setText(getString(R.string.from_day));
                break;
            case 2:
                onDate.setText(getString(R.string.from_weekend));
                break;
            case 3:
                onDate.setText(getString(R.string.from_month));
                break;
            case 4:
                onDate.setText(getString(R.string.from_year));
                break;
        }

        final TextView sort = (TextView) findViewById(R.id.files_search_params_sort);
        sort.setTypeface(Fonts.getMedium(activity));
        sort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showSortDialog(sort);
            }
        });

        switch (params.getSortType()) {
            case FilesConst.SORT_RELEVANCE:
                sort.setText(getString(R.string.on_relevance));
                break;
            case FilesConst.SORT_READSCOUNT:
                sort.setText(getString(R.string.on_popular));
                break;
            case FilesConst.SORT_DATE:
                sort.setText(getString(R.string.on_date));
                break;
        }

        final Button selectButton = (Button) findViewById(R.id.files_search_params_select_button);
        selectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra(FilesConst.SEARCH_PARAMS, params);
                setResult(RESULT_OK, intent);
                finish();
            }
        });
    }

    /**
     * Метод отображает диалог выбора категории
     *
     * @param text компонент отображающий текущее значение
     */
    private void showCategoryDialog(final TextView text) {
        final List<String> items = new ArrayList<>();
        items.add(getString(R.string.all_results));
        if (fileTypesCount.get(0) != 0) {
            items.add(getString(R.string.documents));
        }
        if (fileTypesCount.get(1) != 0) {
            items.add(getString(R.string.images));
        }
        if (fileTypesCount.get(2) != 0) {
            items.add(getString(R.string.videos));
        }
        if (fileTypesCount.get(3) != 0) {
            items.add(getString(R.string.audios));
        }
        if (fileTypesCount.get(4) != 0) {
            items.add(getString(R.string.some));
        }
        AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
        dialog.setTitle(getString(R.string.on_category));
        dialog.setItems(items.toArray(new String[items.size()]), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (items.get(i).equals(getString(R.string.all_results))) {
                    params.setAiType(null);
                    text.setText(getString(R.string.all_results));
                } else if (items.get(i).equals(getString(R.string.documents))) {
                    params.setAiType(FilesConst.AI_DOCUMENT);
                    text.setText(getString(R.string.documents));
                } else if (items.get(i).equals(getString(R.string.images))) {
                    params.setAiType(FilesConst.AI_IMAGE);
                    text.setText(getString(R.string.images));
                } else if (items.get(i).equals(getString(R.string.videos))) {
                    params.setAiType(FilesConst.AI_VIDEO);
                    text.setText(getString(R.string.videos));
                } else if (items.get(i).equals(getString(R.string.audios))) {
                    params.setAiType(FilesConst.AI_AUDIO);
                    text.setText(getString(R.string.audios));
                } else if (items.get(i).equals(getString(R.string.some))) {
                    params.setAiType(FilesConst.AI_APPLICATION);
                    text.setText(getString(R.string.some));
                }
            }
        });
        dialog.setCancelable(true);
        dialog.show();
    }

    /**
     * Метод отображает диалог выбора периода создания файла
     *
     * @param text компонент отображающий текущее значение
     */
    private void showDateDialog(final TextView text) {
        String[] items = {
                getString(R.string.in_all_time),
                getString(R.string.from_day),
                getString(R.string.from_weekend),
                getString(R.string.from_month),
                getString(R.string.from_year)
        };
        AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
        dialog.setTitle(getString(R.string.on_date));
        dialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                DateFormat dateFormat = new SimpleDateFormat(DateUtils.DEFAULT_DATE_STORAGE_SORT);
                Calendar toCalendar = Calendar.getInstance();
                Calendar fromCalendar = Calendar.getInstance();
                switch (i) {
                    case 0: {
                        params.setModifiedFrom(null);
                        params.setModifiedTo(null);
                        params.setSortDate(0);
                        text.setText(getString(R.string.in_all_time));
                    }
                    break;
                    case 1: {
                        fromCalendar.set(fromCalendar.get(Calendar.YEAR), fromCalendar.get(Calendar.MONTH),
                                fromCalendar.get(Calendar.DAY_OF_MONTH) - 1);
                        params.setModifiedFrom(dateFormat.format(fromCalendar.getTime()));
                        params.setModifiedTo(dateFormat.format(toCalendar.getTime()));
                        params.setSortDate(1);
                        text.setText(getString(R.string.from_day));
                    }
                    break;
                    case 2: {
                        fromCalendar.set(fromCalendar.get(Calendar.YEAR), fromCalendar.get(Calendar.MONTH),
                                fromCalendar.get(Calendar.DAY_OF_MONTH) - 6);
                        params.setModifiedFrom(dateFormat.format(fromCalendar.getTime()));
                        params.setModifiedTo(dateFormat.format(toCalendar.getTime()));
                        text.setText(getString(R.string.from_weekend));
                        params.setSortDate(2);
                    }
                    break;
                    case 3: {
                        fromCalendar.set(fromCalendar.get(Calendar.YEAR), fromCalendar.get(Calendar.MONTH) - 1,
                                fromCalendar.get(Calendar.DAY_OF_MONTH));
                        params.setModifiedFrom(dateFormat.format(fromCalendar.getTime()));
                        params.setModifiedTo(dateFormat.format(toCalendar.getTime()));
                        text.setText(getString(R.string.from_month));
                        params.setSortDate(3);
                    }
                    break;
                    case 4: {
                        fromCalendar.set(fromCalendar.get(Calendar.YEAR) - 1, fromCalendar.get(Calendar.MONTH),
                                fromCalendar.get(Calendar.DAY_OF_MONTH));
                        params.setModifiedFrom(dateFormat.format(fromCalendar.getTime()));
                        params.setModifiedTo(dateFormat.format(toCalendar.getTime()));
                        text.setText(getString(R.string.from_year));
                        params.setSortDate(4);
                    }
                    break;
                }
            }
        });
        dialog.setCancelable(true);
        dialog.show();
    }

    /**
     * Метод отображает диалог выбора типа сортировки
     *
     * @param text компонент отображающий текущее значение
     */
    private void showSortDialog(final TextView text) {
        String[] items = {
                getString(R.string.on_relevance),
                getString(R.string.on_popular),
                getString(R.string.on_date)
        };
        AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
        dialog.setTitle(getString(R.string.sort));
        dialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                switch (i) {
                    case 0: {
                        text.setText(getString(R.string.on_relevance));
                        params.setSortType(FilesConst.SORT_RELEVANCE);
                    }
                    break;
                    case 1: {
                        text.setText(getString(R.string.on_popular));
                        params.setSortType(FilesConst.SORT_READSCOUNT);
                    }
                    break;
                    case 2: {
                        text.setText(getString(R.string.on_date));
                        params.setSortType(FilesConst.SORT_DATE);
                    }
                    break;
                }
            }
        });
        dialog.setCancelable(true);
        dialog.show();
    }

}
