package com.pixelnx.sam.jobportal.Activity;

import android.accessibilityservice.GestureDescription;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.ads.AdView;
import com.google.gson.Gson;
import com.pixelnx.sam.jobportal.DTO.ActiveJobDTO;
import com.pixelnx.sam.jobportal.DTO.CommonDTO;
import com.pixelnx.sam.jobportal.DTO.UserSeekerDTO;
import com.pixelnx.sam.jobportal.DTOCI.AllJobs;
import com.pixelnx.sam.jobportal.DTOCI.ModelLanguageDTO;
import com.pixelnx.sam.jobportal.DTOCI.ModelSeekerLogin;
import com.pixelnx.sam.jobportal.DTOCI.ModelSingleJobDisplay;
import com.pixelnx.sam.jobportal.LoginActivity;
import com.pixelnx.sam.jobportal.R;
import com.pixelnx.sam.jobportal.network.NetworkManager;
import com.pixelnx.sam.jobportal.preferences.SharedPrefrence;
import com.pixelnx.sam.jobportal.utils.AppConstans;
import com.pixelnx.sam.jobportal.utils.Consts;
import com.pixelnx.sam.jobportal.utils.CustomButton;
import com.pixelnx.sam.jobportal.utils.CustomEdittext;
import com.pixelnx.sam.jobportal.utils.CustomTextHeader;
import com.pixelnx.sam.jobportal.utils.CustomTextSubHeader;
import com.pixelnx.sam.jobportal.utils.CustomTextview;
import com.pixelnx.sam.jobportal.utils.CustomTextviewBold;
import com.pixelnx.sam.jobportal.utils.ProjectUtils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class FullDetailsActivity extends AppCompatActivity implements View.OnClickListener {//Activity for Seeker job apply
    private SharedPrefrence prefrence;
    private Context mContext;
    private CustomTextviewBold  lgJobPOst, lgjobType, lgDesi, lgjQua, lgspli, lgLast, lgJObDesi, lgProcess;
    private CustomTextview tvHiringProcess, tvOrganisation, tvExperience, tvLocation, tvSkills, tvJobposted, tvJobtype, tvDesignation, tvQualification, tvSpecialization, tvlastDOA, tvJobDescription;
    private CustomButton btnApply;
    private ModelSeekerLogin userSeekerDTO;
    private ImageView ivBack;
    private ArrayList<String> process = new ArrayList<>();
    private ListView lvProcess;
    private AdView mAdView;
    private View adMobView;
    private String job_id = "";
    private boolean isApplied = false;
    private ModelLanguageDTO.Data modelLanguageDTO;
    private CustomTextHeader tvHeader;
    private boolean isValidDate = true;
    private RatingBar ratingreview;
    private CustomEdittext etComment;
    private CustomTextview btComent;
    private CustomTextSubHeader tvRatethisRecruiter,tvSpecialn;
    private ModelSingleJobDisplay jobDisplay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_details);
        mContext = FullDetailsActivity.this;
        prefrence = SharedPrefrence.getInstance(mContext);

        adMobView = findViewById(R.id.adMobView);
        userSeekerDTO = prefrence.getUserDTO(AppConstans.SEEKERDTO);
        modelLanguageDTO = prefrence.getLanguage(AppConstans.LANGUAGE).getData();
        if (getIntent().hasExtra(AppConstans.ACTIVE_JOBS_DTO)) {
            job_id = getIntent().getStringExtra(AppConstans.ACTIVE_JOBS_DTO);
            isApplied = getIntent().getBooleanExtra(AppConstans.IS_APPLIED, false);
        }
        if (!userSeekerDTO.getAdmob().equalsIgnoreCase(""))
            ProjectUtils.showAdd(FullDetailsActivity.this, mAdView, userSeekerDTO.getAdmob(), adMobView);
        init();
    }

    public void init() {
        ratingreview = (RatingBar) findViewById(R.id.ratingreview);
        tvSpecialn = (CustomTextSubHeader) findViewById(R.id.tvSpecialn);
        tvOrganisation = (CustomTextview) findViewById(R.id.tvOrganisation);
        tvExperience = (CustomTextview) findViewById(R.id.tvExperience);
        tvLocation = (CustomTextview) findViewById(R.id.tvLocation);
        tvSkills = (CustomTextview) findViewById(R.id.tvSkills);
        tvJobposted = (CustomTextview) findViewById(R.id.tvJobposted);
        tvJobtype = (CustomTextview) findViewById(R.id.tvJobtype);
        tvDesignation = (CustomTextview) findViewById(R.id.tvDesignation);
        tvQualification = (CustomTextview) findViewById(R.id.tvQualification);
        tvSpecialization = (CustomTextview) findViewById(R.id.tvSpecialization);
        tvlastDOA = (CustomTextview) findViewById(R.id.tvlastDOA);
        tvJobDescription = (CustomTextview) findViewById(R.id.tvJobDescription);
        tvHiringProcess = (CustomTextview) findViewById(R.id.tvHiringProcess);
        btComent = (CustomTextview) findViewById(R.id.btComent);
        etComment = (CustomEdittext) findViewById(R.id.etComment);


        //   lvProcess = (ListView) findViewById(R.id.lvProcess);
        changeLanguage();
        ivBack = (ImageView) findViewById(R.id.ivBack);
        btnApply = (CustomButton) findViewById(R.id.btnApply);
        ivBack.setOnClickListener(this);
        btnApply.setOnClickListener(this);
        if (isApplied) {
            btnApply.setVisibility(View.GONE);
        } else {
            btnApply.setVisibility(View.VISIBLE);
        }

        btComent.setOnClickListener(this);
        getJobDetails();
    }

    private void changeLanguage() {
        lgJobPOst = (CustomTextviewBold) findViewById(R.id.lgJobPOst);
        lgjobType = (CustomTextviewBold) findViewById(R.id.lgjobType);
        lgDesi = (CustomTextviewBold) findViewById(R.id.lgDesi);
        lgjQua = (CustomTextviewBold) findViewById(R.id.lgjQua);
        lgspli = (CustomTextviewBold) findViewById(R.id.lgspli);
        lgLast = (CustomTextviewBold) findViewById(R.id.lgLast);
        lgJObDesi = (CustomTextviewBold) findViewById(R.id.lgJObDesi);
        lgProcess = (CustomTextviewBold) findViewById(R.id.lgProcess);
        tvHeader = (CustomTextHeader) findViewById(R.id.tvHeader);
        tvRatethisRecruiter = (CustomTextSubHeader) findViewById(R.id.tvRatethisRecruiter);

        lgJobPOst.setText(modelLanguageDTO.getJob_post());
        lgjobType.setText(modelLanguageDTO.getJob_type());
        lgDesi.setText(modelLanguageDTO.getDesi());
        lgjQua.setText(modelLanguageDTO.getQua());
        lgspli.setText(modelLanguageDTO.getSp());
        lgLast.setText(modelLanguageDTO.getLast_date_of_a());
        lgJObDesi.setText(modelLanguageDTO.getJob_desc1());
        lgProcess.setText(modelLanguageDTO.getH_pro());
        lgProcess.setText(modelLanguageDTO.getJobs());
        tvHeader.setText(modelLanguageDTO.getJobs());
        tvRatethisRecruiter.setText(modelLanguageDTO.getRate_this_recruiter());
        etComment.setHint(modelLanguageDTO.getWrite_review_fr_recruiter());
        btComent.setHint(modelLanguageDTO.getAdd_review());
    }

    private void getJobDetails() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.SINGLE_JOB_DISPLAY,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.e("APPLY_JOB", response.toString());
                        try {

                            jobDisplay = new Gson().fromJson(response, ModelSingleJobDisplay.class);

                            if (jobDisplay.getStaus().equalsIgnoreCase("true")) {
                                showJobDetails(jobDisplay);
                            } else {
                                ProjectUtils.showToast(FullDetailsActivity.this, jobDisplay.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.showToast(mContext, error.getMessage());
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                //  params.put(Consts.SEEKER_ID, userSeekerDTO.getData().getId());
                params.put(AppConstans.JOB_ID, job_id);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(FullDetailsActivity.this);
        requestQueue.add(stringRequest);
    }


    private void showJobDetails(ModelSingleJobDisplay jobDisplay) {
        ModelSingleJobDisplay.Data jobData = jobDisplay.getData();
        ModelSingleJobDisplay.Recruiter recruiterData = jobDisplay.getRecruiter();
        tvSpecialn.setText(jobData.getSpecialization());
        tvOrganisation.setText(jobData.getAuthor());
        tvExperience.setText(jobData.getExp());
        tvLocation.setText(jobData.getJob_location());
        tvSkills.setText(jobData.getTechnology());
        tvJobposted.setText(jobData.getPost_date());
        tvJobtype.setText(jobData.getJob_type());
        tvDesignation.setText(jobData.getDesignation());
        tvQualification.setText(jobData.getQualification());
        tvSpecialization.setText(jobData.getSpecialization());
        tvJobDescription.setText(jobData.getJob_desc());
        tvlastDOA.setText(jobData.getLasr_date_application());
        try {
            DateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
            DateFormat targetFormat = new SimpleDateFormat("dd/MM/yyyy");
            Date date = originalFormat.parse(jobData.getLasr_date_application());
            String formattedDate = targetFormat.format(date);
            Log.e("DATE", "" + formattedDate);
            tvlastDOA.setText(formattedDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            if (!tvlastDOA.getText().toString().equals("")) {
                Date strDate = sdf.parse(tvlastDOA.getText().toString());
                if (!new Date().before(strDate)) {
                    isValidDate = false;
                    btnApply.setText(modelLanguageDTO.getH_job_not_found());
                }
            }
        } catch (Exception e) {

        }


        StringBuffer stringBuffer = new StringBuffer();
        if (jobData.getWritten_test().equalsIgnoreCase("Yes"))
            stringBuffer.append("Written \n");

        if (jobData.getGroup_discussion().equalsIgnoreCase("Yes"))
            stringBuffer.append("Group Discussion \n");

        if (jobData.getTechnical_round().equalsIgnoreCase("Yes"))
            stringBuffer.append("Technical Round \n");

        if (jobData.getHr_round().equalsIgnoreCase("Yes"))
            stringBuffer.append("HR Round \n");

        tvHiringProcess.setText(stringBuffer);
    }

    public void applyOnJob() {

        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.APPLAY_JOB,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.e("APPLY_JOB", response.toString());
                        try {
                            CommonDTO commonDTO = new CommonDTO();
                            commonDTO = new Gson().fromJson(response, CommonDTO.class);
                            if (commonDTO.getStaus().equalsIgnoreCase("true")) {
                                ProjectUtils.showToast(FullDetailsActivity.this, commonDTO.getMessage());
                                btnApply.setVisibility(View.GONE);
                            } else {
                                ProjectUtils.showToast(FullDetailsActivity.this, commonDTO.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.showToast(mContext, error.getMessage());
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(AppConstans.S_EMAIL, userSeekerDTO.getData().getEmail());
                params.put(AppConstans.JOB_ID, job_id);
                Log.e("APPLY", "" + params);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(FullDetailsActivity.this);
        requestQueue.add(stringRequest);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnApply:

                if (prefrence.getBooleanValue(AppConstans.IS_REGISTER_SEEKER)) {
                    if (userSeekerDTO.getData().getCounter().equals("1")) {
                        try {
                            if (NetworkManager.isConnectToInternet(mContext)) {
                                if (isValidDate) {
                                    applyOnJob();
                                } else {
                                    Log.e("IS EXIS", "This Job is Not Exist");
                                    ProjectUtils.showToast(mContext, modelLanguageDTO.getH_job_not_found());
                                }
                            } else {
                                ProjectUtils.showToast(mContext, getResources().getString(R.string.internet_connection));
                            }
                        } catch (Exception e) {
                        }
                    } else {
                        ProjectUtils.showToast(mContext, modelLanguageDTO.getPro_not_up());
                    }
                } else {
                    ProjectUtils.showAlertDialog(mContext, "", getResources().getString(R.string.guest_login), "Ok", "Cancel", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            startActivity(new Intent(FullDetailsActivity.this, LoginActivity.class));
                            finish();
                            dialogInterface.dismiss();
                        }
                    }, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    });
                }
                break;
            case R.id.btComent:
                rateRecruiter();

                break;

            case R.id.ivBack:

                Intent e = new Intent(FullDetailsActivity.this, SeekerDashboardActivity.class);
                if (prefrence.getBooleanValue(Consts.IS_REGISTER_SEEKER)) {
                    userSeekerDTO = prefrence.getUserDTO(AppConstans.SEEKERDTO);

                } else {

                    e.putExtra(Consts.TAG_GUEST, 2);

                }
                startActivity(e);
                overridePendingTransition(R.anim.enter, R.anim.exit);
                finish();
                break;
        }
    }

    @Override
    public void onPause() {
        if (mAdView != null) {
            mAdView.pause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mAdView != null) {
            mAdView.resume();
        }
    }

    @Override
    public void onDestroy() {
        if (mAdView != null) {
            mAdView.destroy();
        }
        super.onDestroy();
    }

    private void rateRecruiter() {
        ProjectUtils.showProgressDialog(mContext, false, "Adding Review");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.SET_RATING,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.e("RATING_RECRUITER", response.toString());
                        try {
                            ProjectUtils.pauseProgressDialog();
                            CommonDTO commonDTO = new CommonDTO();
                            commonDTO = new Gson().fromJson(response, CommonDTO.class);
                            if (commonDTO.getStaus().equalsIgnoreCase("true")) {
                                ProjectUtils.showToast(FullDetailsActivity.this, commonDTO.getMessage());
                                btnApply.setVisibility(View.GONE);
                            } else {
                                ProjectUtils.showToast(FullDetailsActivity.this, commonDTO.getMessage());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.pauseProgressDialog();
                        ProjectUtils.showToast(mContext, error.getMessage());
                    }
                }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(AppConstans.RATING, "" + ratingreview.getNumStars());
                params.put(AppConstans.COMMENT, ProjectUtils.getEditTextValue(etComment));
                params.put(AppConstans.SEEKER_EMAIL, userSeekerDTO.getData().getEmail());
                params.put(AppConstans.RE_EMAIL, jobDisplay.getRecruiter().getEmail());
                Log.e("RATING", "" + params);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(FullDetailsActivity.this);
        requestQueue.add(stringRequest);
    }
}
