AvailableJobsActivity

AvailableJobsActivity
mail@pastecode.io avatar
unknown
plain_text
2 years ago
36 kB
2
Indexable
Never
package com.gn.networkon.activities.availableJobs

import android.animation.Animator
import android.content.Context
import android.content.Intent
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.annotation.ColorRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import com.daimajia.androidanimations.library.Techniques
import com.daimajia.androidanimations.library.YoYo
import com.gn.networkon.BuildConfig
import com.gn.networkon.Constants.CommonStrings
import com.gn.networkon.Constants.CommonStrings.DateFormat.AVAILABLE_DATE_FORMAT
import com.gn.networkon.Constants.CommonStrings.DateFormat.AVAILABLE_JOB_TEXT_FORMAT
import com.gn.networkon.Constants.CommonStrings.Keys.Prefs
import com.gn.networkon.Constants.CommonStrings.TASK_LINKING_STATUS
import com.gn.networkon.NetworkAdapter.APIError
import com.gn.networkon.NetworkAdapter.CommonParams
import com.gn.networkon.NetworkAdapter.ResponseResolver
import com.gn.networkon.NetworkAdapter.RestClient
import com.gn.networkon.R
import com.gn.networkon.activities.availableJobs.adapters.GetAvailableAdapter
import com.gn.networkon.activities.availableJobs.calendar.BaseEvent
import com.gn.networkon.activities.availableJobs.calendar.Event
import com.gn.networkon.activities.availableJobs.calendar.utils.Day
import com.gn.networkon.activities.availableJobs.calendar.utils.Week
import com.gn.networkon.common.AppManager
import com.gn.networkon.common.LocalStorage
import com.gn.networkon.location.LocationUtils
import com.gn.networkon.models.locals.AvailableTaskJobs
import com.gn.networkon.models.responses.enpResponse.EnpResponse
import com.gn.networkon.models.responses.getAllTasks.AllDateDataList
import com.gn.networkon.models.responses.getAllTasks.ValuesItem
import com.gn.networkon.models.responses.getAvailableTaskData.AvailableData
import com.gn.networkon.models.responses.getAvailableTaskData.AvailableJobList
import com.gn.networkon.utilities.CommonUtils
import com.gn.networkon.utilities.applendoCalenderView.CalendarDay
import com.gn.networkon.utilities.applendoCalenderView.EventDay
import com.gn.networkon.utilities.applendoCalenderView.exceptions.OutOfDateRangeException
import com.gn.networkon.utilities.applendoCalenderView.listeners.OnCalendarPageChangeListener
import com.gn.networkon.utilities.applendoCalenderView.listeners.OnDayClickListener
import com.gn.networkon.utilities.applendoCalenderView.utils.parseColor
import kotlinx.android.synthetic.main.activity_available_job.*
import timber.log.Timber
import java.text.DateFormat
import java.text.Format
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*

class AvailableJobsActivity : AppCompatActivity(), CalendarFragment.FragmentDateListener {

    private val list: ArrayList<CalendarDay> = ArrayList()
    private val availableTaskJobs: ArrayList<AvailableTaskJobs> = ArrayList()
    private lateinit var selectedCalendarDate: Calendar
    private var currentDate = ""
    private var todayDate = ""
    private var day = 0
    private var month = 0
    private var isViewOpen = false
    private var year = 0
    var currentPosition = 0
    val events = mutableListOf<Event>()
    val dataList: ArrayList<AvailableJobList> = ArrayList()
    val tasks: ArrayList<ValuesItem> = ArrayList()

    private val jobClick = object : JobClick {
        override fun setClick(isRecurringTask: Boolean, availableTaskJobs: AvailableTaskJobs) {
            if (isRecurringTask) {
                callAcceptApi(availableTaskJobs)
            } else {
                callChangeJobStatus(availableTaskJobs)
            }
        }
    }

    private fun callChangeJobStatus(availableTaskJobs: AvailableTaskJobs) {

        val getParams = CommonParams.Builder()
                .add("job_id", availableTaskJobs.jobId)
                .add("job_assignment_id",0)
                .add("lat", LocationUtils.getLastLatLng(this).latitude)
                .add("lng", LocationUtils.getLastLatLng(this).longitude)
                .add("job_status", availableTaskJobs.task_status)


        RestClient.getApiInterface(this).changeJobStatus(getParams.build().map).enqueue(object : ResponseResolver<EnpResponse?>(this, true, true) {

            override fun failure(error: APIError<*>) {
                Log.d("---", error.message)
            }

            override fun retry() {
                callChangeJobStatus(availableTaskJobs)
            }

            override fun success(t: EnpResponse?) {
                setJobsOnPager()
            }
        })
    }

    private fun callAcceptApi(availableTaskJobs: AvailableTaskJobs) {
        val getParams = CommonParams.Builder()
        getParams.add("id", availableTaskJobs.jobId)
        getParams.add("date", getSendingDateFormat(availableTaskJobs.getUtcDatetime))
        RestClient.getApiInterface(this).accecptRequest(getParams.build().map).enqueue(object : ResponseResolver<EnpResponse?>(this, false, true) {

            override fun failure(error: APIError<*>?) {
                vDateProgress.visibility = View.GONE
            }

            override fun retry() {
                callAcceptApi(availableTaskJobs)
            }

            override fun success(enpResponse: EnpResponse?) {
                setJobsOnPager()
                rvAvailableJobs.visibility = View.GONE
                finish()
                startActivity(Intent(applicationContext,AvailableJobsActivity::class.java))
            }
        })
    }

    private fun getSendingDateFormat(utcDatetime: String?): String {
        val getTargetZone = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
        val originalFormat = if (LocalStorage.with(this).getString(CommonStrings.Keys.Prefs.DATE_TIME_FORMAT, "").isNullOrEmpty()) {
            SimpleDateFormat(CommonStrings.DateFormat.STANDARD_DATE_FORMAT_TZ, CommonUtils.getDateFormatLocale(this))
        } else {
            SimpleDateFormat(LocalStorage.with(this).getString(CommonStrings.Keys.Prefs.DATE_TIME_FORMAT, ""), CommonUtils.getDateFormatLocale(this))
        }

        val getDate = originalFormat.parse(utcDatetime)
        return getTargetZone.format(getDate)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_available_job)

        setStrings()

        setCalendar()

        setFragment()

        clicks()

        getJobData(todayDate)
    }

    private fun setJobsOnPager() {
        viewCalendar.eventRequestCallback = {
            populate(it)
        }
        viewCalendar.onEventClickListener = {
            isViewOpen = true
            val getAvailableList: ArrayList<AvailableTaskJobs> = ArrayList()
            val getSelected = dataList[it.positionOfList]
            getSelected.tasks.mapIndexed { i, valuesItem ->
                val getTaskStatus = if (getSelected.tasks.size == 1) {
                    TASK_LINKING_STATUS.ONLY_TASK.status
                } else if (i == 0) {
                    TASK_LINKING_STATUS.FIRST_TASK.status
                } else if (i == getSelected.tasks.size - 1) {
                    TASK_LINKING_STATUS.LAST_TASK.status
                } else {
                    TASK_LINKING_STATUS.NONE.status
                }
                val getJobIdData = if (getSelected.job_id != null) valuesItem.getJobId() else getSelected.recurring_id
                val isRecurringTask = getSelected.job_id == null
                getAvailableList.add(AvailableTaskJobs(valuesItem.getName(), valuesItem.getLocation(),
                        valuesItem.utcDatetime, valuesItem.utcDatetime, valuesItem.getTaskType(),
                        getTaskStatus, getJobIdData, isRecurringTask, valuesItem.lat, valuesItem.lng,
                        valuesItem.getTaskStatus(), getSelected.tasks[0].getTaskId()))
            }
            val getAdapter = GetAvailableAdapter(this, getAvailableList).apply {
                adapterJobClick = jobClick
            }
            rvAvailableJobs.isVisible = true
            cardView.isVisible = false
            rvAvailableJobs.adapter = getAdapter
        }
        /*viewCalendar.onEventLongClickListener = {
            Toast.makeText(this, it.title + " long clicked", Toast.LENGTH_SHORT).show()
        }
        viewCalendar.onAddEventListener = {
            val start = DateUtils.formatDateTime(this, it.start, DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_TIME)
            Toast.makeText(this, "Add event at $start", Toast.LENGTH_SHORT).show()
            true
        }*/
    }

    @Suppress("MagicNumber")
    private fun populate(week: Week, force: Boolean = true) {
        if (!force && viewCalendar.cachedEvents.contains(week))
            return
        events.clear()
        dataList.mapIndexed { index, availableJobList ->
            tasks.clear()
            tasks.add(availableJobList.tasks[0])
            val getTitle = if (availableJobList.tasks[0].name.isNullOrEmpty()) {
                availableJobList.tasks[0].location
            } else {
                availableJobList.tasks[0].name
            }
            val isSingleTaskId = availableJobList.tasks.size <= 1
            //val shouldReduce30Minutes = availableJobList.start_datetime == availableJobList.end_datetime
            val getJobIdData = availableJobList.job_id ?: availableJobList.recurring_id

            val startDateTime = availableJobList.tasks[0].getUtcDatetime()
            val endDateTime = availableJobList.tasks[availableJobList.tasks.size - 1].getUtcDatetime()
            events.add(BaseEvent(
                    getTitle,
                    availableJobList.tasks[0].taskDescription,
                    R.color.colorPrimary,
                    getTime(startDateTime, isSingleTaskId),
                    getTime(endDateTime, false),
                    false, getJobIdData.toString(),
                    availableJobList.tasks[0].utcDatetime,
                    index))
        }
        /*for (i in 0..15) {
            val id = nextId++.toString()
            val start = week.start + abs(random.nextLong()) % DateUtils.WEEK_IN_MILLIS
            events.add(BaseEvent(
                    id,
                    id,
                    (random.nextInt() or 0xFF000000.toInt()) and 0x00202020.inv(),
                    start,
                    start + abs(random.nextLong()) % (DateUtils.DAY_IN_MILLIS / 8)))
        }
        for (i in 0..3) {
            val id = nextId++.toString()
            val start = week.start + abs(random.nextLong()) % DateUtils.WEEK_IN_MILLIS
            events.add(BaseEvent(
                    id,
                    id,
                    (random.nextInt() or 0xFF000000.toInt()) and 0x00202020.inv(),
                    start,
                    start + abs(random.nextLong()) % (DateUtils.DAY_IN_MILLIS * 7),
                    true))
        }*/
        viewCalendar.setEventsForWeek(week, events)
    }

    private fun getJobData(todayDate: String) {
        val startDateTime = CommonUtils.getLocalToUTCDateTimeAvailableJob(this, "$todayDate 00:00")
        val endDateTime = CommonUtils.getLocalToUTCDateTimeAvailableJob(this, "$todayDate 23:59")
        val getParams = CommonParams.Builder()
        getParams.add("end_date", endDateTime)
        getParams.add("start_date", startDateTime)
        RestClient.getApiInterface(this).getAvailableTasks(getParams.build().map).enqueue(object : ResponseResolver<AvailableData>(this, true, true) {

            override fun success(availableData: AvailableData?) {
                Timber.tag("AvailableJobList").e(availableData?.data.toString())
                if ((availableData?.data != null) && (availableData.data.size != 0)) {
                    dataList.clear()
                    dataList.addAll(availableData.data)
                }
                setJobsOnPager()
                viewCalendar.changeAdapter(todayDate, currentPosition)

                val originalFormat = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
                val getDate = originalFormat.parse(todayDate)
                val cal = Calendar.getInstance()
                cal.time = getDate
                viewCalendar.visibleStart = Day(cal.get(Calendar.YEAR), cal.get(Calendar.WEEK_OF_YEAR), cal.get(Calendar.DAY_OF_WEEK))
                viewCalendar.changeAdapter(todayDate, currentPosition)
            }

            override fun failure(error: APIError<*>?) {
            }

            override fun retry() {
                getJobData(todayDate)
            }

        })
    }

    private fun getTime(startDatetime: String?, shouldReduce30Minutes: Boolean): Long {
        var startDate = 0L
        try {
            var getTargetZone: SimpleDateFormat? = null
            val originalFormat = if (LocalStorage.with(this).getString(CommonStrings.Keys.Prefs.DATE_TIME_FORMAT, "").isNullOrEmpty()) {
                getTargetZone = SimpleDateFormat(CommonStrings.DateFormat.STANDARD_DATE_FORMAT_TZ, CommonUtils.getDateFormatLocale(this))
                SimpleDateFormat(CommonStrings.DateFormat.STANDARD_DATE_FORMAT_TZ, CommonUtils.getDateFormatLocale(this))
            } else {
                getTargetZone = SimpleDateFormat(LocalStorage.with(this).getString(CommonStrings.Keys.Prefs.DATE_TIME_FORMAT, ""), CommonUtils.getDateFormatLocale(this))
                SimpleDateFormat(LocalStorage.with(this).getString(CommonStrings.Keys.Prefs.DATE_TIME_FORMAT, ""), CommonUtils.getDateFormatLocale(this))
            }
            originalFormat.timeZone = TimeZone.getTimeZone("UTC")
            val date: Date = originalFormat.parse(startDatetime)
            getTargetZone.timeZone = TimeZone.getTimeZone("en")
            val getOrig = getTargetZone.format(date)
            val finalDate = getTargetZone.parse(getOrig)
            val in30Minutes = (30 * 60 * 1000).toLong()
            startDate = if (shouldReduce30Minutes) finalDate.time.minus(in30Minutes) else finalDate.time
        } catch (e: ParseException) {
            e.printStackTrace()
        }
        return startDate
    }

    private fun setFragment() {
        supportFragmentManager.beginTransaction().add(R.id.flContainer, CalendarFragment(), "CalendarFragment").commit()
    }

    private fun setStrings() {
        calendarView.setHeaderColor(R.color.colorPrimary)
        tvHeaderName.text = getCurrentMonth(getCurrentDate(false))
        tvSelectedDate.text = getCurrentDate(true)
        val sdfFormat = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
        todayDate = sdfFormat.format(Date())
    }

    private fun getCurrentMonth(currentDate: String): String {
        val cal = Calendar.getInstance()
        cal.time = SimpleDateFormat(AVAILABLE_DATE_FORMAT, CommonUtils.getDateFormatLocale(this)).parse(currentDate)
        val formatter: Format = SimpleDateFormat("MMMM", CommonUtils.getDateFormatLocale(this))
        return formatter.format(cal.time)
    }

    private fun setCalendar() {
        list.clear()
        val calendarDay = CalendarDay(Calendar.getInstance())
        if (BuildConfig.FLAVOR == CommonStrings.flavorsName.dash || BuildConfig.FLAVOR == CommonStrings.flavorsName.eathappynow || BuildConfig.FLAVOR == CommonStrings.flavorsName.cupboardwagon) {
            calendarDay.backgroundDrawable = getDayCircle(applicationContext, R.color.colorPrimary, R.color.colorPrimary)
        } else {
            calendarDay.backgroundDrawable = getDayCircle(applicationContext, R.color.accent_55, R.color.accent_55)
        }

        if (BuildConfig.FLAVOR == CommonStrings.flavorsName.pidi || BuildConfig.FLAVOR == CommonStrings.flavorsName.dash || BuildConfig.FLAVOR == CommonStrings.flavorsName.eathappynow || BuildConfig.FLAVOR == CommonStrings.flavorsName.cupboardwagon) {
            calendarDay.labelColor = R.color.white
        } else {
            calendarDay.labelColor = R.color.colorPrimaryDark
        }

        list.add(calendarDay)
        calendarView.setCalendarDays(list)
        try {
            calendarView.setDate(Calendar.getInstance())
        } catch (e: OutOfDateRangeException) {
            e.printStackTrace()
        }
        selectedCalendarDate = Calendar.getInstance()
        calendarView.setOnForwardPageChangeListener(object : OnCalendarPageChangeListener {
            override fun onChange() {
                renderNextMonth()
            }
        })

        calendarView.setOnPreviousPageChangeListener(object : OnCalendarPageChangeListener {
            override fun onChange() {
                renderPreviousMonth()
            }
        })

        calendarView.setOnDayClickListener(object : OnDayClickListener {
            override fun onDayClick(eventDay: EventDay) {
                list.clear()
                val calendarDay = CalendarDay(eventDay.calendar)
                if (BuildConfig.FLAVOR == CommonStrings.flavorsName.dash || BuildConfig.FLAVOR == CommonStrings.flavorsName.eathappynow || BuildConfig.FLAVOR == CommonStrings.flavorsName.cupboardwagon) {
                    calendarDay.backgroundDrawable = getDayCircle(applicationContext, R.color.colorPrimary, R.color.colorPrimary)
                } else {
                    calendarDay.backgroundDrawable = getDayCircle(applicationContext, R.color.accent_55, R.color.accent_55)
                }
                if (BuildConfig.FLAVOR == CommonStrings.flavorsName.pidi || BuildConfig.FLAVOR == CommonStrings.flavorsName.dash || BuildConfig.FLAVOR == CommonStrings.flavorsName.eathappynow || BuildConfig.FLAVOR == CommonStrings.flavorsName.cupboardwagon) {
                    calendarDay.labelColor = R.color.white
                } else {
                    calendarDay.labelColor = R.color.colorPrimaryDark
                }
                list.add(calendarDay)
                calendarView.setCalendarDays(list)
                try {
                    calendarView.setDate(eventDay.calendar)
                } catch (e: OutOfDateRangeException) {
                    e.printStackTrace()
                }
                rlCalendarContainer.visibility = View.INVISIBLE
                cardView.isVisible = true
                day = eventDay.calendar[Calendar.DAY_OF_MONTH]
                val sdfFormat = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
                currentDate = sdfFormat.format(eventDay.calendar.time)
                todayDate = currentDate
                selectedCalendarDate = eventDay.calendar
                currentPosition = 1
                setDateData(todayDate)
            }
        })
        renderCurrentMonth()
    }

    private fun renderNextMonth() {
        var getMonthOnlyForNextFetchValue = 0
        if (month == Calendar.DECEMBER) {
            month = Calendar.JANUARY
            ++year
        } else {
            getMonthOnlyForNextFetchValue = month
            ++month
        }
        getAllDateData(false)
    }

    private fun renderPreviousMonth() {
        var getMonthOnlyForFetchValue = 0
        if (month == Calendar.JANUARY) {
            month = Calendar.DECEMBER
            --year
        } else {
            getMonthOnlyForFetchValue = month
            --month
        }
        getAllDateData(false)
    }

    private fun renderCurrentMonth() {
        val calendar = Calendar.getInstance()
        val currentMonth = calendar[Calendar.MONTH]
        val currentYear = calendar[Calendar.YEAR]
        month = currentMonth
        year = currentYear
        day = calendar[Calendar.DAY_OF_MONTH]
    }

    private fun getAllDateData(isCurrentMonth: Boolean) {
        vDateProgress.visibility = View.VISIBLE
        val getParams = getParamsForData()

        RestClient.getApiInterface(this).getAvailableTaskDates(getParams.build().map).enqueue(object : ResponseResolver<AllDateDataList?>(this, false, true) {

            override fun failure(error: APIError<*>?) {
                vDateProgress.visibility = View.GONE
            }

            override fun retry() {
                getAllDateData(isCurrentMonth)
            }

            override fun success(allDateDataList: AllDateDataList?) {
                vDateProgress.visibility = View.GONE
                AppManager.getInstance().isShouldApiHit = false
                val df: DateFormat
                val formatter: DateFormat
                if (LocalStorage.with(this@AvailableJobsActivity).getString(Prefs.DATE_TIME_FORMAT, "") == "" || LocalStorage.with(this@AvailableJobsActivity).getString(Prefs.DATE_TIME_FORMAT, "") == null) {
                    df = SimpleDateFormat("dd/MM/yyyy", CommonUtils.getDateFormatLocale(this@AvailableJobsActivity))
                    formatter = SimpleDateFormat("yyyy-MM-dd", CommonUtils.getDateFormatLocale(this@AvailableJobsActivity))
                } else {
                    Log.e("TAG", "--------------------" + LocalStorage.with(this@AvailableJobsActivity).getString(Prefs.DATE_FORMAT, ""))
                    df = SimpleDateFormat(LocalStorage.with(this@AvailableJobsActivity).getString(Prefs.DATE_FORMAT, ""), CommonUtils.getDateFormatLocale(this@AvailableJobsActivity))
                    formatter = SimpleDateFormat(LocalStorage.with(this@AvailableJobsActivity).getString(Prefs.DATE_FORMAT, ""), CommonUtils.getDateFormatLocale(this@AvailableJobsActivity))
                }
                val currentDayTime = Calendar.getInstance()
                val highlightedDates: MutableList<Calendar> = ArrayList()
                for (i in allDateDataList!!.data.indices) {
                    val date = allDateDataList.data[i]
                    val cal = Calendar.getInstance()
                    val temp = Calendar.getInstance()
                    try {
                        cal.time = df.parse(date)
                        if (currentDate != null) {
                            temp.time = formatter.parse(currentDate)
                            currentDayTime.time = formatter.parse(currentDate)
                        } else {
                            temp.time = formatter.parse(todayDate)
                        }
                    } catch (e: ParseException) {
                        e.printStackTrace()
                    }
                    if (cal.time != temp.time) {
                        highlightedDates.add(cal)
                    }
                }
                calendarView.selectedDates = highlightedDates
                if (isCurrentMonth) {
                    val list: MutableList<CalendarDay> = ArrayList()
                    val date: Date = selectedCalendarDate.time
                    val cal = Calendar.getInstance()
                    cal.time = date
                    val calendarDay = CalendarDay(cal)
                    if (BuildConfig.FLAVOR == CommonStrings.flavorsName.dash || BuildConfig.FLAVOR == CommonStrings.flavorsName.eathappynow || BuildConfig.FLAVOR == CommonStrings.flavorsName.cupboardwagon || BuildConfig.FLAVOR == CommonStrings.flavorsName.pooli) {
                        calendarDay.backgroundDrawable = getDayCircle(applicationContext, R.color.colorPrimary, R.color.colorPrimary)
                    } else {
                        calendarDay.backgroundDrawable = getDayCircle(applicationContext, R.color.accent_55, R.color.accent_55)
                    }
                    if (BuildConfig.FLAVOR == CommonStrings.flavorsName.pidi || BuildConfig.FLAVOR == CommonStrings.flavorsName.dash || BuildConfig.FLAVOR == CommonStrings.flavorsName.eathappynow || BuildConfig.FLAVOR == CommonStrings.flavorsName.cupboardwagon || BuildConfig.FLAVOR == CommonStrings.flavorsName.pooli) {
                        calendarDay.labelColor = R.color.white
                    } else {
                        calendarDay.labelColor = R.color.colorPrimaryDark
                    }
                    list.add(calendarDay)
                    calendarView.setCalendarDays(list)
                    try {
                        calendarView.setDate(cal)
                    } catch (e: OutOfDateRangeException) {
                        e.printStackTrace()
                    }
                }
            }
        })
    }

    private fun getParamsForData(): CommonParams.Builder {
        val getParams = CommonParams.Builder()
        val calendar = Calendar.getInstance(Locale.ENGLISH)
        calendar[year, month] = calendar.getActualMinimum(Calendar.DAY_OF_MONTH)
        val monthFirstDay = calendar.time
        calendar[year, month] = calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
        val monthLastDay = calendar.time
        val df = SimpleDateFormat(CommonStrings.DateFormat.AVAILABLE_SEND_DATE_FORMAT, Locale.ENGLISH)
        df.timeZone = TimeZone.getTimeZone("UTC")
        val startDateStr = df.format(monthFirstDay)
        val endDateStr = df.format(monthLastDay)
        getParams.add("start_date", startDateStr)
        getParams.add("end_date", endDateStr)
        getParams.add("get_upcoming_dates", true)
        return getParams
    }

    private fun clicks() {
        llBack.setOnClickListener {
            if (isViewOpen){
                rvAvailableJobs.isVisible = false
                cardView.isVisible = true
                isViewOpen = false
            }else{
                finish()
            }

        }

        llCalendar.setOnClickListener {
            renderCalender(false)
        }
        vCalendarBackground.setOnClickListener {
            renderCalender(true)
        }
    }

    private fun renderCalender(isCalendarVisible: Boolean) {
        cardView.isVisible = isCalendarVisible
        if (isViewOpen){
            rvAvailableJobs.isVisible = false
            cardView.isVisible = true
            isViewOpen = false
        }
        if (!isCalendarVisible) {
            YoYo.with(Techniques.BounceInDown).duration(500).withListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animator: Animator) {
                    getAllDateData(true)
                    //getAllDateData(true);
                    vCalendarBackground.visibility = View.VISIBLE
                    rlCalendarContainer.visibility = View.VISIBLE
                }

                override fun onAnimationEnd(animator: Animator) {}
                override fun onAnimationCancel(animator: Animator) {}
                override fun onAnimationRepeat(animator: Animator) {}
            }).playOn(rlCalendarContainer)
        } else {
            YoYo.with(Techniques.SlideOutUp).duration(300).withListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animator: Animator) {
                    vCalendarBackground.visibility = View.GONE
                }

                override fun onAnimationEnd(animator: Animator) {
                    rlCalendarContainer.visibility = View.INVISIBLE
                }

                override fun onAnimationCancel(animator: Animator) {}
                override fun onAnimationRepeat(animator: Animator) {}
            }).playOn(rlCalendarContainer)
        }
    }

    @JvmName("getCurrentDate1")
    private fun getCurrentDate(value: Boolean): String {
        val selectedCalendarDate = Calendar.getInstance(CommonUtils.getDateFormatLocale(this))
        val formatter = if (value) {
            SimpleDateFormat(AVAILABLE_JOB_TEXT_FORMAT, CommonUtils.getDateFormatLocale(this))
        } else {
            SimpleDateFormat(CommonStrings.DateFormat.AVAILABLE_DATE_FORMAT, CommonUtils.getDateFormatLocale(this))
        }
        return formatter.format(selectedCalendarDate.time)
    }

    fun getDayCircle(context: Context, @ColorRes borderColor: Int, @ColorRes fillColor: Int): Drawable? {
        val drawable = ContextCompat.getDrawable(context, R.drawable.background_circle_date) as GradientDrawable?
        drawable!!.setStroke(0, context.parseColor(borderColor))
        drawable.setColor(context.parseColor(fillColor))
        return drawable
    }

    override fun onResume() {

        super.onResume()
    }
    override fun onDateChanged(currentDateFrom: String) {
        tvHeaderName.text = getCurrentMonth(currentDateFrom)

        val originalFormat = SimpleDateFormat(AVAILABLE_DATE_FORMAT, CommonUtils.getDateFormatLocale(this))
        val getDate = originalFormat.parse(currentDateFrom)

        val format = SimpleDateFormat(AVAILABLE_JOB_TEXT_FORMAT, CommonUtils.getDateFormatLocale(this))
        val getDateForShow = format.format(getDate)
        tvSelectedDate.text = getDateForShow


        val sdfFormat = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
        todayDate = sdfFormat.format(getDate)
        getJobData(todayDate)
    }

    private fun setDateData(todayDate: String) {
        getJobData(todayDate)
        val originalFormat = SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)
        val getDate = originalFormat.parse(todayDate)

        val originalFormat1 = SimpleDateFormat(AVAILABLE_JOB_TEXT_FORMAT, CommonUtils.getDateFormatLocale(this))
        val getDateForShow = originalFormat1.format(getDate)
        tvSelectedDate.text = getDateForShow

        val newFormat = SimpleDateFormat(AVAILABLE_DATE_FORMAT, CommonUtils.getDateFormatLocale(this))
        val newDate = newFormat.format(getDate)

        tvHeaderName.text = getCurrentMonth(newDate)
    }
}


/*jobDialog = AlertDialog.Builder(this, R.style.CustomAlertDialog).create()
            val inflater = this.layoutInflater
            val paymentDialogView: View = inflater.inflate(R.layout.layout_tasks_invitation_item, null)
            val llTimer: FrameLayout = paymentDialogView.findViewById(R.id.llTimer)
            val llTaskName: RelativeLayout = paymentDialogView.findViewById(R.id.llTaskName)
            val tvInvitationItemCustomerName: TextView = paymentDialogView.findViewById(R.id.tvInvitationItemCustomerName)
            val tvTaskInvitationItemDate: TextView = paymentDialogView.findViewById(R.id.tvTaskInvitationItemDate)
            val tvStatus: ImageView = paymentDialogView.findViewById(R.id.tvInvitationItemTaskStatus)
            val tvStatusName: TextView = paymentDialogView.findViewById(R.id.tvStatusName)
            val tvTaskInvitationItemAddress: TextView = paymentDialogView.findViewById(R.id.tvTaskInvitationItemAddress)
            val no: TextView = paymentDialogView.findViewById(R.id.no)
            val yes: TextView = paymentDialogView.findViewById(R.id.yes)
            val llEarningEstimateLayout: LinearLayout = paymentDialogView.findViewById(R.id.llEarningEstimateLayout)
            jobDialog!!.setView(paymentDialogView)


            llTimer.isVisible = false
            llEarningEstimateLayout.isVisible = false

            no.text = StringFetcher.getString(this, R.string.decline)
            yes.text = StringFetcher.getString(this, R.string.accept)

            val getTask = tasks[it.positionOfList]
            val getAllTask = dataList[it.positionOfList]
            tvInvitationItemCustomerName.apply {
                text = if (getTask.name.isNullOrEmpty()) "" else getTask.name
            }

            llTaskName.isVisible = !getTask.name.isNullOrEmpty()

            tvTaskInvitationItemAddress.text = getTask.getLocation()
            tvTaskInvitationItemDate.text = if (LocalStorage.with(this).getString(Prefs.DATE_TIME_FORMAT, "") == "" || LocalStorage.with(this).getString(Prefs.DATE_TIME_FORMAT, "") == null) {
                if (getTask.getTaskType() == 2) {
                    if (getTask.getEndDatetime() != null) {
                        CommonUtils.convertTZToLocal(this, getTask.getUtcDatetime(), CommonStrings.DateFormat.END_USER_DATE_TIME_FORMAT) + " - " +
                                CommonUtils.convertTZToLocal(this, FirebaseNotifications.serviceEndDateTime, CommonStrings.DateFormat.END_USER_DATE_TIME_FORMAT)
                    } else {
                        CommonUtils.convertTZToLocal(this, getTask.getUtcDatetime(), CommonStrings.DateFormat.END_USER_DATE_TIME_FORMAT) + " - " +
                                CommonUtils.convertTZToLocal(this, FirebaseNotifications.serviceEndDateTime, CommonStrings.DateFormat.END_USER_DATE_TIME_FORMAT)
                    }
                } else {
                    CommonUtils.convertTZToLocal(this, getTask.getUtcDatetime(), CommonStrings.DateFormat.END_USER_DATE_TIME_FORMAT)
                }
            } else {
                if (getTask.getTaskType() == 2) {
                    if (getTask.getEndDatetime() != null) {
                        CommonUtils.convertTZToLocal(this, getTask.getUtcDatetime(), LocalStorage.with(this).getString(Prefs.DATE_TIME_FORMAT, "")) + " - " +
                                CommonUtils.convertTZDynamicForPushes(this, FirebaseNotifications.serviceEndDateTime, LocalStorage.with(this).getString(Prefs.DATE_TIME_FORMAT, ""))
                    } else {
                        CommonUtils.convertTZToLocal(this, getTask.getUtcDatetime(), LocalStorage.with(this).getString(Prefs.DATE_TIME_FORMAT, "")) + " - " +
                                CommonUtils.convertTZDynamicForPushes(this, FirebaseNotifications.serviceEndDateTime, LocalStorage.with(this).getString(Prefs.DATE_TIME_FORMAT, ""))
                    }
                } else {
                    CommonUtils.convertTZDynamicForPushes(this, getTask.getUtcDatetime(), LocalStorage.with(this).getString(Prefs.DATE_TIME_FORMAT, ""))
                }
            }


            if (getTask.getTaskType() == 0) {
                if (BuildConfig.FLAVOR == CommonStrings.flavorsName.pidi) {
                    tvStatus.setBackgroundDrawable(resources.getDrawable(R.drawable.ic_pickup_pd))
                } else {
                    tvStatus.setBackgroundDrawable(resources.getDrawable(R.drawable.ic_pickup_background))
                }
                tvStatusName.text = StringFetcher.getString(this, R.string.pick_up)
            } else if (getTask.getTaskType() == 1) {
                if (BuildConfig.FLAVOR == CommonStrings.flavorsName.pidi) {
                    tvStatus.setBackgroundDrawable(resources.getDrawable(R.drawable.ic_delivery_pd))
                } else {
                    tvStatus.setBackgroundDrawable(resources.getDrawable(R.drawable.ic_delivery_background))
                }
                tvStatusName.text = StringFetcher.getString(this, R.string.delivery)
            } else if (getTask.getTaskType() == 2) {
                if (BuildConfig.FLAVOR == CommonStrings.flavorsName.pidi) {
                    tvStatus.setBackgroundDrawable(resources.getDrawable(R.drawable.ic_pickup_pd))
                } else {
                    tvStatus.setBackgroundDrawable(resources.getDrawable(R.drawable.ic_pickup_background))
                }
                tvStatusName.text = StringFetcher.getString(this, R.string.service)
            }

            no.setOnClickListener {
                jobDialog!!.dismiss()
            }

            yes.setOnClickListener {
                jobDialog!!.dismiss()
            }
            jobDialog!!.show()*/