package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.ogaclejapan.smarttablayout.SmartTabLayout;
import com.cygnusa.hyperm.fancyshowcase.FancyShowCaseView;
import com.cygnusa.hyperm.fancyshowcase.FocusShape;
import com.cygnusa.hyperm.fragments.QuestionFragment;
import com.cygnusa.hyperm.roundcornerprogressbar.RoundCornerProgressBar;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.CustomViewPager;
import com.cygnusa.hyperm.util.DepthPageTransformerNew;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.AnswerResponse;
import com.cygnusa.hyperm.wrappers.AssessmentAnswer;
import com.cygnusa.hyperm.wrappers.AssessmentList;
import com.cygnusa.hyperm.wrappers.AssessmentQuestion;
import com.cygnusa.hyperm.wrappers.AssessmentQuestionResponse;
import com.cygnusa.hyperm.wrappers.AssessmentScore;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.HitCountModel;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class AssessmentActivity extends AppCompatActivity {
    public static AssessmentList ASSESSMENT = new AssessmentList();
    public static String TRAINING_ID = "";
    public static String CATEGORY_ID = "";
    public static boolean isOffline = false;
    ApiService restService;
    TransparentProgressDialog progressDialog;
    TextView title;
    ArrayList<AssessmentQuestion> ASSESSMENT_QUESTIONS = new ArrayList<>();
    CustomViewPager viewPager;
    SmartTabLayout indicatorTab;
    ImageButton previous, next;
    RoundCornerProgressBar linearTimerView;
    TextView time;
    Button submitButton;
    String START_TIME = "";
    String END_TIME = "";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    AlertDialog.Builder alertDialogBuilder;
    AlertDialog alertDialog;
    Bundle bundle;
    Handler handler = new Handler();
    private boolean isBlinking = false;
    String fromTime, toTime, finalTime;
    Calendar c;
    SimpleDateFormat df;
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (linearTimerView.getProgress() == 0) {
                onSubmitAnswer(true);
                time.setText("TIME LEFT");
            } else {
                linearTimerView.setProgress(linearTimerView.getProgress() - 1);
                long millis = (long) (linearTimerView.getProgress() * 1000);
                String formattedTime = String.format("%02d:%02d",
                        TimeUnit.MILLISECONDS.toMinutes(millis) % TimeUnit.HOURS.toMinutes(1),
                        TimeUnit.MILLISECONDS.toSeconds(millis) % TimeUnit.MINUTES.toSeconds(1));
                time.setText(formattedTime);
                updateProgressColor();
                handler.postDelayed(runnable, 1000);
            }
        }
    };
    private FirebaseAnalytics firebaseAnalytics;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_assessment);
        setupWindowAnimations();
        restService = ((MainApplication) getApplication()).getClient();
        viewPager = findViewById(R.id.viewPager);
        title = findViewById(R.id.title);
        indicatorTab = findViewById(R.id.indicatorTab);
        submitButton = findViewById(R.id.submitButton);
        submitButton.setVisibility(View.GONE);
        linearTimerView = findViewById(R.id.linearTimerView);

        previous = findViewById(R.id.previous);
        next = findViewById(R.id.next);
        time = findViewById(R.id.time);

        time.setVisibility(View.VISIBLE);
        linearTimerView.setVisibility(View.GONE);

        firebaseAnalytics = FirebaseAnalytics.getInstance(this);
        FirebaseAnalytics.getInstance(this).setAnalyticsCollectionEnabled(true);

        bundle = new Bundle();
        bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "1");
        bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Assessment Activity");
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);
        title.setText(ASSESSMENT.getAssessmentname() + "");
        title.setSelected(true);

        if (ASSESSMENT.getAssessmenttimetype().trim().equalsIgnoreCase("0")) {
            time.setVisibility(View.INVISIBLE);
            linearTimerView.setVisibility(View.INVISIBLE);
        }


        viewPager.post(new Runnable() {
            @Override
            public void run() {
                getAssesmentQuistion();
            }
        });

        previous.setEnabled(false);
        next.setEnabled(false);

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    previous.setEnabled(false);
                    next.setEnabled(true);
                    if (ASSESSMENT_QUESTIONS.size() == 1) {
                        submitButton.setVisibility(View.VISIBLE);
                    }
                } else if (position == ASSESSMENT_QUESTIONS.size() - 1) {
                    previous.setEnabled(true);
                    next.setEnabled(false);
                    submitButton.setVisibility(View.VISIBLE);
                } else {
                    previous.setEnabled(true);
                    next.setEnabled(true);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        previous.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewPager.getCurrentItem() > 0) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() - 1, true);
                }
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (viewPager.getCurrentItem() < ASSESSMENT_QUESTIONS.size() - 1) {
                    viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
                }
            }
        });

        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getToTime();
                onSubmitAnswer(false);
            }
        });

        findViewById(R.id.helpIcon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHelpScreen();
            }
        });

        getCurrentTime();


    }


    private void getCurrentTime() {
        c = Calendar.getInstance();
        System.out.println("fromTime " + c.getTime());

        df = new SimpleDateFormat("HH:mm:ss");
        fromTime = df.format(c.getTime());
        Log.e("fromTime", fromTime);
    }

    private void sendHitCountToServer() {
        restService.sendAllHitCount(buildConfigData()).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {

                } else {
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if (t.getMessage() != null) {
                    Log.e("responeHit", t.getMessage());
                }
            }
        });
    }

    private HitCountModel buildConfigData() {
        HitCountModel hitCountModel = new HitCountModel();
        hitCountModel.setPage("Assessment");
        hitCountModel.setViewtime("0");
        return hitCountModel;
    }


    private void onSubmitAnswer(boolean isAutoSubmit) {
        if (ASSESSMENT_QUESTIONS != null && ASSESSMENT_QUESTIONS.size() > 0) {
            ArrayList<AssessmentAnswer> answers = new ArrayList<>();
            END_TIME = format.format(new Date());
            for (AssessmentQuestion question : ASSESSMENT_QUESTIONS) {
                AssessmentAnswer answer = new AssessmentAnswer();
                answer.setAqid(question.getAqid());
                answer.setQid(question.getQid());
                if (isAutoSubmit) {
                    answer.setOptions(question.getAnswer());
                } else {
                    if (question.getIs_mandatory().trim().equalsIgnoreCase("1")) {
                        if (!question.isAnswered()) {
                            viewPager.setCurrentItem(ASSESSMENT_QUESTIONS.indexOf(question));
                            GlobalData.showToast(AssessmentActivity.this, "Please answer all mandatory questions", Toast.LENGTH_SHORT).show();
                            return;
                        } else {
                            answer.setOptions(question.getAnswer());
                        }
                    } else {
                        answer.setOptions(question.getAnswer());
                    }
                }
                answers.add(answer);
            }

            Gson gson = new Gson();
            JsonElement jsonElement = gson.toJsonTree(
                    answers, new TypeToken<ArrayList<AssessmentAnswer>>() {
                    }.getType());

            HashMap<String, String> map = new HashMap<>();
            map.put("ans_arr", jsonElement.toString());
            map.put("startdatetime", START_TIME);
            map.put("enddatetime", END_TIME);

            if (new UtilService().isNetworkAvailable(AssessmentActivity.this)) {

                progressDialog = new TransparentProgressDialog(AssessmentActivity.this);
                progressDialog.show();

                restService.postAssessment(ASSESSMENT.getAssessmentid(), map).enqueue(new Callback<AnswerResponse>() {
                    @Override
                    public void onResponse(Call<AnswerResponse> call, Response<AnswerResponse> response) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (response.body() != null && response.body().getStatus() == 200) {
                            try {
                                int d = (int) Math.round(Double.parseDouble(response.body().getData().getPercentage_score()));
                                showPopup(response.body().getData(), String.valueOf(d), response.body().getAssessment_msg());
                                GlobalData.showToast(getBaseContext(), response.body().getAssessment_msg(), Toast.LENGTH_LONG).show();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            try {
                                handler.removeCallbacksAndMessages(null);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            finish();
                        } else if (response.body() != null) {
                            GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                try {
                                    handler.removeCallbacksAndMessages(null);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<AnswerResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                Cursor cursor = GlobalData.sdb.rawQuery("select * from assessment_question where category_id='"
                        + CATEGORY_ID + "' and training_id='" + TRAINING_ID + "'", null);

                if (isOffline || cursor.getCount() > 0) {
                    GlobalData.sdb.execSQL("delete from assessment_answer where assessment_id='"
                            + ASSESSMENT.getAssessmentid()
                            + "' and category_id='" + CATEGORY_ID + "' and training_id='" + TRAINING_ID + "'");
                    JsonElement jsonElement1 = gson.toJsonTree(
                            map, new TypeToken<HashMap<String, String>>() {
                            }.getType());
                    ContentValues values = new ContentValues();
                    values.put("assessment_answer", jsonElement1.toString());
                    values.put("training_id", TRAINING_ID);
                    values.put("category_id", CATEGORY_ID);
                    values.put("assessment_id", ASSESSMENT.getAssessmentid());
                    GlobalData.sdb.insert("assessment_answer", null, values);
                    GlobalData.showToast(getBaseContext(), "Assessment saved on local, will sync to server when online", Toast.LENGTH_LONG).show();
                    try {
                        handler.removeCallbacksAndMessages(null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    finish();
                    AssessmentActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                            R.anim.animation_f_leave);
                } else {
                    GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
                }
            }

        }
    }

    private void showPopup(final AssessmentScore assessmentScore, String s, String msg) {
        View view = LayoutInflater.from(AssessmentActivity.this).inflate(
                R.layout.assessment_popup, null);
        view.findViewById(R.id.continueButton).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                        try {
                            handler.removeCallbacksAndMessages(null);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        finish();
                        AssessmentActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                                R.anim.animation_f_leave);
                    }
                });

        view.findViewById(R.id.reviewButton).setOnClickListener(
                new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                        ReviewActivity.ASSESSMENT = ASSESSMENT;
                        ReviewActivity.ASSESSMENT_SCORE = assessmentScore;
                        startActivity(new Intent(AssessmentActivity.this, ReviewActivity.class));
                        try {
                            handler.removeCallbacksAndMessages(null);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        finish();
                    }
                });

        TextView linkView = view.findViewById(R.id.score);
        TextView assesmentName = view.findViewById(R.id.assesmentName);
        if (Integer.parseInt(s) < 80) {
            linkView.setTextColor(getColor(R.color.red));
        } else {
            linkView.setTextColor(getColor(R.color.green));
        }
        linkView.setText(s);

        TextView assesmentMessage = view.findViewById(R.id.assesmentMessage);
        assesmentMessage.setText(msg);

        assesmentName.setText("For " + ASSESSMENT.getAssessmentname());
        alertDialogBuilder = new AlertDialog.Builder(AssessmentActivity.this);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setView(view);
        alertDialog = alertDialogBuilder.create();
        alertDialog.show();
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            confirmClose();
        }
        return super.onOptionsItemSelected(item);
    }

    private void confirmClose() {
        new AlertDialog.Builder(AssessmentActivity.this)
                .setMessage("Are you sure you want to exit the assessment?")
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(
                                    DialogInterface dialog,
                                    int which) {
                                try {
                                    handler.removeCallbacksAndMessages(null);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                                getToTime();

                                finish();
                                AssessmentActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                                        R.anim.animation_f_leave);
                            }
                        }).setNegativeButton("No", null).show();
    }

    private void getToTime() {

        c = Calendar.getInstance();
        System.out.println("toTime " + c.getTime());

        df = new SimpleDateFormat("HH:mm:ss");
        toTime = df.format(c.getTime());
        Log.e("toTime", toTime);

        finalTime = UtilService.getTimeInterval(this, df, fromTime, toTime);

        if (GlobalData.user.getData().getRole().equalsIgnoreCase("9"))
            sendHitCountToServer();

    }

    @Override
    public void onBackPressed() {

        confirmClose();
    }

    @SuppressLint("StaticFieldLeak")
    private void getAssesmentQuistion() {
        progressDialog = new TransparentProgressDialog(AssessmentActivity.this);
        progressDialog.show();

        if (new UtilService().isNetworkAvailable(AssessmentActivity.this)) {
            restService.getAssesmentQuistion(ASSESSMENT.getAssessmentid()).enqueue(new Callback<AssessmentQuestionResponse>() {
                @Override
                public void onResponse(Call<AssessmentQuestionResponse> call, Response<AssessmentQuestionResponse> response) {

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    ASSESSMENT_QUESTIONS = new ArrayList<>();
                    if (response.body() != null && response.body().getStatus() == 200) {
                        ASSESSMENT_QUESTIONS = response.body().getData();
                        bundle = new Bundle();
                        bundle.putString("Assessment_questions", "Get All Assessment Questions");
                        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

                        Cursor cursor = GlobalData.sdb.rawQuery("select * from assessment_question where assessment_id='"
                                + ASSESSMENT.getAssessmentid()
                                + "' and category_id='" + CATEGORY_ID + "' and training_id='" + TRAINING_ID + "'", null);
                        if (cursor.getCount() > 0) {
                            GlobalData.sdb.execSQL("delete from assessment_question where assessment_id='"
                                    + ASSESSMENT.getAssessmentid()
                                    + "' and category_id='" + CATEGORY_ID + "' and training_id='" + TRAINING_ID + "'");
                            Gson gson = new Gson();
                            JsonElement jsonElement = gson.toJsonTree(
                                    ASSESSMENT_QUESTIONS, new TypeToken<ArrayList<AssessmentQuestion>>() {
                                    }.getType());
                            ContentValues values = new ContentValues();
                            values.put("assessment_question", jsonElement.toString());
                            values.put("training_id", TRAINING_ID);
                            values.put("category_id", CATEGORY_ID);
                            values.put("assessment_id", ASSESSMENT.getAssessmentid());
                            GlobalData.sdb.insert("assessment_question", null, values);
                        }

                        setAssesmentQuistion();
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        try {
                            handler.removeCallbacksAndMessages(null);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        finish();
                    } else if (response.body() != null) {
                        GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            try {
                                handler.removeCallbacksAndMessages(null);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            finish();
                        }
                    }
                }

                @Override
                public void onFailure(Call<AssessmentQuestionResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            new AsyncTask<Void, Void, String>() {
                @Override
                protected String doInBackground(Void... params) {
                    try {
                        Cursor cursor = GlobalData.sdb.rawQuery("select * from assessment_question where category_id='"
                                + CATEGORY_ID + "' and training_id='" + TRAINING_ID + "' and assessment_id='"
                                + ASSESSMENT.getAssessmentid() + "'", null);
                        ASSESSMENT_QUESTIONS = new ArrayList<>();
                        if (cursor.getCount() != 0) {
                            cursor.moveToFirst();
                            Gson gson = new Gson();
                            ASSESSMENT_QUESTIONS = gson.fromJson(
                                    cursor.getString(cursor.getColumnIndex("assessment_question")),
                                    new TypeToken<ArrayList<AssessmentQuestion>>() {
                                    }.getType());
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(String s) {
                    super.onPostExecute(s);
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    if (ASSESSMENT_QUESTIONS.size() == 0) {
                        GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
                    }
                    setAssesmentQuistion();
                }
            }.execute();
        }
    }

    private void setAssesmentQuistion() {
        viewPager.setPageTransformer(true, new DepthPageTransformerNew());
        if (ASSESSMENT_QUESTIONS != null && ASSESSMENT_QUESTIONS.size() > 0) {
            viewPager.setAdapter(new AssesmentQuistionAdapter(getSupportFragmentManager()));
            indicatorTab.setViewPager(viewPager);
            viewPager.setPagingEnabled(true);
        } else {
            GlobalData.showToast(AssessmentActivity.this, "No Assessment Found", Toast.LENGTH_LONG).show();
           // onBackPressed();
            finish();
        }
        if (ASSESSMENT_QUESTIONS != null && ASSESSMENT_QUESTIONS.size() > 0) {
            previous.setEnabled(false);
            next.setEnabled(true);
            if (ASSESSMENT_QUESTIONS.size() == 1) {
                submitButton.setVisibility(View.VISIBLE);
            }
        }
        if (ASSESSMENT_QUESTIONS != null && ASSESSMENT_QUESTIONS.size() > 0) {
            viewPager.setOffscreenPageLimit(ASSESSMENT_QUESTIONS.size());
        }

        if (ASSESSMENT.getAssessmenttimetype().trim().equalsIgnoreCase("1")) {
            if (!ASSESSMENT.getAssessmenttime().trim().isEmpty()) {
                int seconds = Integer.parseInt(ASSESSMENT.getAssessmenttime().trim()) * 60;
//                seconds = 60;
                linearTimerView.setMax(seconds);
                linearTimerView.setProgress(seconds);
                handler.post(runnable);
            }
        }

        START_TIME = format.format(new Date());

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (getPreferences(MODE_PRIVATE).getBoolean("AssessmentActivity", true)) {
                    showHelpScreen();
                    getPreferences(MODE_PRIVATE).edit().putBoolean("AssessmentActivity", false).apply();
                }
            }
        }, 1000);
    }

    private void manageBlinkEffect() {
        if (isBlinking) {
            return;
        }

        isBlinking = true;
        Animation anim = new AlphaAnimation(0.0f, 1.0f);
        anim.setDuration(1000);
        anim.setStartOffset(20);
        anim.setRepeatMode(Animation.REVERSE);
        anim.setRepeatCount(Animation.INFINITE);
        time.startAnimation(anim);
    }

    private void updateProgressColor() {
        float progress = linearTimerView.getProgress() / linearTimerView.getMax() * 100;
        if (progress < 60) {
            time.setTextColor(Color.parseColor("#F44336"));
            linearTimerView.setProgressColor(Color.parseColor("#F44336"));
            manageBlinkEffect();
        } else {
            linearTimerView.setProgressColor(Color.parseColor("#00344c"));
            time.setTextColor(Color.parseColor("#00344c"));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (GlobalData.canLogout) {
            try {
                handler.removeCallbacksAndMessages(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            finish();
        }
    }

    private void showHelpScreen() {
        bundle = new Bundle();
        bundle.putString("Assessment_help_screen", "Assessment Help Screen");
        firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);

        try {
            new FancyShowCaseView.Builder(this)
                    .focusOn((View) indicatorTab.getParent())
                    .title("Tap on the arrows to navigate next or previous questions")
                    .titleSize(22, 1)
                    .closeOnTouch(true)
                    .fitSystemWindows(false)
                    .focusShape(FocusShape.CIRCLE)
                    .backgroundColor(Color.parseColor("#99000000"))
                    .build()
                    .show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class AssesmentQuistionAdapter extends FragmentStatePagerAdapter {

        private AssesmentQuistionAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            QuestionFragment fragment = new QuestionFragment();
            fragment.setTrainingId(TRAINING_ID);
            fragment.setAssessmentQuestion(ASSESSMENT_QUESTIONS.get(position));
            fragment.setQuestionNo(String.valueOf((position + 1)));
            return fragment;
        }

        @Override
        public int getCount() {
            return ASSESSMENT_QUESTIONS.size();
        }


        @Override
        public CharSequence getPageTitle(int position) {
            return String.valueOf((position + 1));
        }
    }
}