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

import android.app.ActionBar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.TimePicker;

import com.pnikosis.materialishprogress.ProgressWheel;

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.SettingsConst;
import kz.arta.synergy.workflow.mobile.android.common.components.DatePickerFragment;
import kz.arta.synergy.workflow.mobile.android.common.components.TimePickerFragment;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.models.offline.completion.OfflineCompletionResult;
import kz.arta.synergy.workflow.mobile.android.common.offline.add.AddResultWork;
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.common.utils.Utils;
import kz.arta.synergy.workflow.mobile.android.works.manager.completion.RejectWork;
import kz.arta.synergy.workflow.mobile.android.works.models.WorkItem;

/**
 * Created by neox on 12.05.14.
 * Отклонение результата работы
 */
public class RejectWorkActivity extends FragmentActivity {

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

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

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

    /**
     * Дата начала
     */
    private String startDate;

    /**
     * Дата завершения
     */
    private String finishDate;

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

    /**
     * Прогресс работы
     */
    private String progress;

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

    /**
     * Текст работы
     */
    private String workName;

    /**
     * Настройки
     */
    private SharedPreferences settings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

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

        activity = this;

        ActionBar actionBar = getActionBar();
        if (actionBar != null) {
            actionBar.hide();
            ((TextView) findViewById(R.id.title_action_bar_reject)).setTypeface(Fonts.getMedium(activity));
        }

        settings = activity.getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE);

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

        Intent intent = getIntent();
        person = (Person) intent.getSerializableExtra(ActivityConst.PERSON);
        workID = intent.getStringExtra(ActivityConst.WORK_ID);
        workName = intent.getStringExtra(ActivityConst.WORK_NAME);
        startDate = intent.getStringExtra(ActivityConst.START_DATE);
        finishDate = intent.getStringExtra(ActivityConst.FINISH_DATE);
        progress = intent.getStringExtra(ActivityConst.PROGRESS_REJECT);
        resultID = intent.getStringExtra(ActivityConst.RESULT_ID);

        initComponents();
    }

    /**
     * Инициализация компонентов
     */
    private void initComponents() {

        final TextView startDate = (TextView) findViewById(R.id.reject_work_start_data);
        startDate.setTypeface(Fonts.getMedium(activity));
        startDate.setText(DateUtils.parseData(this.startDate, DateUtils.DEFAULT_EDIT_TEXT_DATE, DateUtils.DEFAULT_DATE_FORMAT));
        startDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDatePicker(startDate);
            }
        });

        final TextView startTime = (TextView) findViewById(R.id.reject_work_start_time);
        startTime.setTypeface(Fonts.getMedium(activity));
        startTime.setText(DateUtils.parseData(this.startDate, DateUtils.DEFAULT_EDIT_TEXT_TIME, DateUtils.DEFAULT_DATE_FORMAT));
        startTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePicker(startTime);
            }
        });

        final TextView finishDate = (TextView) findViewById(R.id.reject_work_finish_data);
        finishDate.setTypeface(Fonts.getMedium(activity));
        finishDate.setText(DateUtils.parseData(this.finishDate, DateUtils.DEFAULT_EDIT_TEXT_DATE, DateUtils.DEFAULT_DATE_FORMAT));
        finishDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDatePicker(finishDate);
            }
        });

        final TextView finishTime = (TextView) findViewById(R.id.reject_work_finish_time);
        finishTime.setTypeface(Fonts.getMedium(activity));
        finishTime.setText(DateUtils.parseData(this.finishDate, DateUtils.DEFAULT_EDIT_TEXT_TIME, DateUtils.DEFAULT_DATE_FORMAT));
        finishTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showTimePicker(finishTime);
            }
        });

        final TextView progressText = (TextView) findViewById(R.id.reject_work_progress);
        progressText.setTypeface(Fonts.getMedium(activity));
        if (progress.equals("100")) {
            progress = "99";
        }
        progressText.setText(progress + "%");

        final SeekBar seekBar = (SeekBar) findViewById(R.id.reject_work_seek_bar);
        seekBar.setMax(99);
        seekBar.setProgress(Integer.valueOf(progress));
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                progressText.setText(String.valueOf(i) + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        final EditText commentText = (EditText) findViewById(R.id.reject_work_comment);

        final Button rejectBtn = (Button) findViewById(R.id.reject_work_button);
        rejectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String stDate = DateUtils.parseData(startDate.getText().toString() + " " + startTime.getText().toString(),
                        DateUtils.DEFAULT_DATE_FORMAT, DateUtils.DEFAULT_EDIT_TEXT_DATE + " " + DateUtils.DEFAULT_EDIT_TEXT_TIME);
                String fnDate = DateUtils.parseData(finishDate.getText().toString() + " " + finishTime.getText().toString(),
                        DateUtils.DEFAULT_DATE_FORMAT, DateUtils.DEFAULT_EDIT_TEXT_DATE + " " + DateUtils.DEFAULT_EDIT_TEXT_TIME);
                // если есть интернет - отклоняем работу
                if (Utils.isOnline(activity, person.getHost())) {
                    RejectWork rejectWork = new RejectWork();
                    rejectWork.setActivity(activity);
                    rejectWork.setPerson(person);
                    rejectWork.setStartDate(stDate);
                    rejectWork.setFinishDate(fnDate);
                    rejectWork.setWorkID(workID);
                    rejectWork.setResultID(resultID);
                    rejectWork.setProgressBar(progressBar);
                    rejectWork.setProgress(String.valueOf(seekBar.getProgress()));
                    rejectWork.setComment(commentText.getText().toString());
                    rejectWork.execute();
                } else if (Utils.checkSyncEnables(settings)) {
                    // если да - записываем в базу данных данные отклоненной работы
                    OfflineCompletionResult completionResult = new OfflineCompletionResult();
                    completionResult.setActionID(workID);
                    completionResult.setStartDate(stDate);
                    completionResult.setFinishDate(fnDate);
                    completionResult.setResultID(resultID);
                    completionResult.setName(workName);
                    completionResult.setSignal("reject");
                    completionResult.setComment(commentText.getText().toString());
                    completionResult.setProgress(String.valueOf(seekBar.getProgress()));
                    // объект AcceptRejectWork
                    AddResultWork arWork = new AddResultWork(activity);
                    arWork.reject(completionResult);
                    // работа
                    WorkItem work = new WorkItem();
                    work.setActionID(workID);
                    // закрыаем активити с отправкой данных
                    Intent intent = new Intent();
                    intent.putExtra(ActivityConst.REJECT_OFFLINE, work);
                    intent.putExtra("progress", String.valueOf(seekBar.getProgress()));
                    intent.putExtra("comment", commentText.getText().toString());
                    setResult(RESULT_OK, intent);
                    finish();
                }
            }
        });
    }

    /**
     * Открывает диалог выбора даты
     *
     * @param edit - TextView
     */
    private void showDatePicker(final TextView edit) {
        DatePickerFragment date = new DatePickerFragment();
        Bundle args = new Bundle();
        args.putInt(DateUtils.YEAR, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                "yyyy", DateUtils.DEFAULT_EDIT_TEXT_DATE)));
        args.putInt(DateUtils.MONTH, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                "MM", DateUtils.DEFAULT_EDIT_TEXT_DATE)) - 1);
        args.putInt(DateUtils.DAY, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                "dd", DateUtils.DEFAULT_EDIT_TEXT_DATE)));
        date.setArguments(args);
        date.setCallBack(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
                edit.setText(DateUtils.changePickerDialog(dayOfMonth) + " / " + DateUtils.changePickerDialog(monthOfYear + 1)
                        + " / " + String.valueOf(year));
            }
        });
        date.show(getSupportFragmentManager(), "Date Picker");
    }

    /**
     * Открывает диалог выбора времени
     *
     * @param edit - TextView
     */
    private void showTimePicker(final TextView edit) {
        TimePickerFragment date = new TimePickerFragment();
        Bundle args = new Bundle();
        args.putInt(DateUtils.HOUR, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                "HH", DateUtils.DEFAULT_EDIT_TEXT_TIME)));
        args.putInt(DateUtils.MINUTES, Integer.parseInt(DateUtils.parseData(edit.getText().toString(),
                "mm", DateUtils.DEFAULT_EDIT_TEXT_TIME)));
        date.setArguments(args);
        date.setCallBack(new TimePickerDialog.OnTimeSetListener() {
            @Override
            public void onTimeSet(TimePicker timePicker, int hour, int minute) {
                edit.setText(DateUtils.changePickerDialog(hour) + ":" + DateUtils.changePickerDialog(minute));
            }
        });
        date.show(getSupportFragmentManager(), "Time Picker");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
}
