package aero.ru.gpn.cci.tzamobile.fragments


import aero.ru.gpn.cci.tzamobile.R
import aero.ru.gpn.cci.tzamobile.activities.CancelTaskActivity
import aero.ru.gpn.cci.tzamobile.activities.MainActivity
import aero.ru.gpn.cci.tzamobile.activities.SuspendRefuelingActivity
import aero.ru.gpn.cci.tzamobile.models.LostConnectionStates
import aero.ru.gpn.cci.tzamobile.models.TaskStateEnum
import aero.ru.gpn.cci.tzamobile.models.task.*
import aero.ru.gpn.cci.tzamobile.network.utils.ServerChecker
import aero.ru.gpn.cci.tzamobile.states.task.fueling.aircraft.*
import aero.ru.gpn.cci.tzamobile.utilities.*
import aero.ru.gpn.cci.tzamobile.view.TaskStepView
import aero.ru.gpn.cci.tzamobile.viewmodels.AircraftFuellingTaskViewModel
import aero.ru.gpn.cci.tzamobile.viewmodels.getAircraftFuellingTaskViewModelFactory
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.internal.disposables.EmptyDisposable
import kotlinx.android.synthetic.main.fragment_task.*
import org.threeten.bp.*
import java.util.*

private const val TASK_ID = "taskId"
private const val REQUEST_CODE = 743

class AircraftFuellingTaskFragment : BaseNavigationFragment(),
    Chronometer.OnChronometerTickListener {

    // ---------------- Data ----------------

    private lateinit var taskId: UUID

    private lateinit var containerLayout: FrameLayout

    private lateinit var taskStepsLinearLayout: LinearLayout

    private lateinit var taskStepScrollView: ScrollView

    private var triggeredExit = false

    private val viewModel by viewModels<AircraftFuellingTaskViewModel> {
        getAircraftFuellingTaskViewModelFactory(
            taskId
        )
    }

    private val taskStepViews = TreeMap<Int, TaskStepView>()

    private var taskFactStartTime: LocalDateTime? = null

    private val serverChecker by lazy(LazyThreadSafetyMode.NONE) {
        ServerChecker.getInstance(
            requireContext()
        )
    }

    // --------------- Disposables --------------

    private var withdrawalOnTextChangeDisposable: Disposable = EmptyDisposable.INSTANCE
    private var fuelingTotalRecountDisposable: Disposable = EmptyDisposable.INSTANCE
    private var deliveryReceiptOnDataChangeDisposable: Disposable = EmptyDisposable.INSTANCE
    private var deliveryReceiptCorrectionDisposable: Disposable = EmptyDisposable.INSTANCE

    // --------------- Observers --------------

    private val exceptionObserver = Observer<Throwable?> {
        if (it == null) return@Observer
    }

    private val stepDataObserver = Observer<List<StepData>> {
        if (it == null) return@Observer

        processStepData(it)
    }

    private val aircraftRefuellingStateObserver = Observer<AircraftRefuellingState> {
        if (it == null) return@Observer

        processAircraftStates(it)
    }

    private val noConnectionAlertObserver = Observer<LostConnectionStates> {
        if (it == null) return@Observer

        val noConnectionDialog = createNoConnectionDialog(it)
        noConnectionDialog.show()
    }

    private val isOnlineObserver = Observer<Boolean> {
        if (it == null) return@Observer

        viewModel.isOnline.set(it)
    }

    // ---------------- View states ----------------

    private lateinit var additionalRefuelingState: AdditionalRefuelingState

    private lateinit var fuelInfoState: FuelInfoState

    private lateinit var preparationForRefuelingState: PreparationForRefuelingState

    private lateinit var receiptInfoCheckingState: ReceiptInfoCheckingState

    private lateinit var receiptInfoInputState: ReceiptInfoInputState

    private lateinit var receiptPrintingState: ReceiptPrintingState

    private lateinit var taskCompletionState: TaskCompletionState

    private lateinit var waitingForApproveState: WaitingForApproveState

    private lateinit var receiptCorrectionState: ReceiptCorrectionState


    // ---------------- Other variables ----------------

    private val disposables = CompositeDisposable()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        taskId = arguments?.getSerializable(TASK_ID) as UUID
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? = inflater.inflate(R.layout.fragment_task, container, false).also {
        containerLayout = it.findViewById(R.id.infoStepTaskFrameLayout)
        taskStepsLinearLayout = it.findViewById(R.id.task_steps_linear_layout)
        taskStepScrollView = it.findViewById(R.id.taskStepScrollView)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

        triggeredExit = false

        headerCallback?.showBackButton(false)

        viewModel.exceptionLiveData.removeObserver(exceptionObserver)
        viewModel.stepDataLiveData.removeObserver(stepDataObserver)
        viewModel.aircraftStateLiveData.removeObserver(aircraftRefuellingStateObserver)

        populateViewStates()

        viewModel.exceptionLiveData.observe(viewLifecycleOwner, exceptionObserver)
        viewModel.stepDataLiveData.observe(viewLifecycleOwner, stepDataObserver)
        viewModel.aircraftStateLiveData.observe(viewLifecycleOwner, aircraftRefuellingStateObserver)
        viewModel.noConnectionStateLiveData.observe(viewLifecycleOwner, noConnectionAlertObserver)
        serverChecker.serverStatusLiveData.observe(viewLifecycleOwner, isOnlineObserver)

        rejectButton.setOnClickListener {
            startActivity(CancelTaskActivity.newInstance(requireContext(), taskId))
        }

        view.visible()
    }

    override fun onStart() {
        super.onStart()

        viewModel.start()
    }

    private fun populateViewStates() {
        additionalRefuelingState =
            AdditionalRefuelingState.getInstance(requireActivity(), layoutInflater, containerLayout)
                .also { disposables.add(it) }

        fuelInfoState =
            FuelInfoState.getInstance(requireActivity(), layoutInflater, containerLayout)
                .also { disposables.add(it) }

        preparationForRefuelingState =
            PreparationForRefuelingState.getInstance(
                requireActivity(),
                layoutInflater,
                containerLayout
            )
                .also { disposables.add(it) }

        receiptInfoCheckingState =
            ReceiptInfoCheckingState.getInstance(requireActivity(), layoutInflater, containerLayout)
                .also { disposables.add(it) }

        receiptInfoInputState =
            ReceiptInfoInputState.getInstance(requireActivity(), layoutInflater, containerLayout)
                .also { disposables.add(it) }

        receiptPrintingState =
            ReceiptPrintingState.getInstance(requireActivity(), layoutInflater, containerLayout)
                .also { disposables.add(it) }

        taskCompletionState =
            TaskCompletionState.getInstance(requireActivity(), layoutInflater, containerLayout)
                .also { disposables.add(it) }

        waitingForApproveState =
            WaitingForApproveState.getInstance(requireActivity(), layoutInflater, containerLayout)
                .also { disposables.add(it) }

        receiptCorrectionState =
            ReceiptCorrectionState.getInstance(requireActivity(), layoutInflater, containerLayout)
                .also { disposables.add(it) }
    }

    private fun processStepData(stepData: List<StepData>) {
        var view: TaskStepView

        for (data in stepData) {
            view = taskStepViews.getOrPut(data.stepNumber, this::populateTaskStepView)

            when (data) {
                is NormalStep -> populateNormalStepView(view, data)
                is ExecutableStep -> {
                    populateExecutableStepView(view, data)

                    if (data.stepNumber >= 4)
                        taskStepScrollView.fullScroll(ScrollView.FOCUS_DOWN)
                }
                is CompletedStep -> populateCompleteStepView(view, data)
            }
        }

        taskStepViews.forEach { (_, view) -> taskStepsLinearLayout.addViewIfNotExist(view) }
    }

    private fun populateTaskStepView(): TaskStepView = TaskStepView(requireActivity())

    private fun populateNormalStepView(view: TaskStepView, stepData: NormalStep) {
        val background = getTaskStepViewBackgroundForNonExecutableStep(stepData.stepNumber)

        populateBaseData(view, stepData)

        view.clearCompleteTime()

        view.setBackgroundState(background)
    }

    private fun populateCompleteStepView(view: TaskStepView, stepData: CompletedStep) {
        val background = getTaskStepViewBackgroundForNonExecutableStep(stepData.stepNumber)

        populateBaseData(view, stepData)

        view.apply {
            setBackgroundState(background)
            setCompleteTime(stepData.completeDateTime)
        }
    }

    private fun populateExecutableStepView(view: TaskStepView, stepData: ExecutableStep) {
        populateBaseData(view, stepData)
        view.setBackgroundState(TaskStepView.GREEN_BACKGROUND)

        view.clearCompleteTime()
    }

    private fun populateBaseData(view: TaskStepView, stepData: StepData) {
        view.apply {
            isChecked = stepData.isChecked
            stepNumber = stepData.stepNumber
            setStepName(stepData.stepName)
        }
    }

    private fun processAircraftStates(aircraftRefuellingState: AircraftRefuellingState) {
        when (aircraftRefuellingState) {
            is Loading -> {
            }//TODO крутилка для запросов сущностей с бэка

            is StartedState -> drawStartedState(aircraftRefuellingState)

            is ArrivedAtPlatformState -> drawArrivedAtPlatformState(aircraftRefuellingState)

            is TookPositionForFueling -> drawTookPositionForFueling(aircraftRefuellingState)

            is RefuelingRequestSent -> drawRefuelingRequestSent(aircraftRefuellingState)

            is ReadyForFuellingState -> drawReadyForFuellingState(aircraftRefuellingState)

            is FuelingState -> drawFuelingState(aircraftRefuellingState)

            is SuspendedFuelingState -> drawSuspendedFuelingState(aircraftRefuellingState)

            is ContinuedFuelingState -> drawContinuedFuelingState(aircraftRefuellingState)

            is FinishedFuelingState -> drawFinishedFuelingState(aircraftRefuellingState)

            is DeliveryReceiptCreatedState -> drawDeliveryReceiptCreatedState(
                aircraftRefuellingState
            )

            is ReceiptApproveRequestedState -> drawReceiptApproveRequestedState(
                aircraftRefuellingState
            )

            is ReceiptRequestApprovedState -> {
            }//TODO а нужен ли он?

            is AdditionalFuelingRequiredState -> drawAdditionalFuelingRequiredState(
                aircraftRefuellingState
            )

            is DeliveryReceiptConfirmedState -> drawDeliveryReceiptConfirmedState(
                aircraftRefuellingState
            )

            is DeliveryReceiptCorrectionState -> drawDeliveryReceiptCorrectionState(aircraftRefuellingState)

            is FinishedFuellingTaskState -> drawFinishedFuellingTaskState(aircraftRefuellingState)

            is LeftPlatformState -> drawLeftPlatformState()

            is AircraftTaskInitialState -> initTaskData(aircraftRefuellingState)
        }
    }

    private fun drawStartedState(stateData: StartedState) {
        preparationForRefuelingState.apply {

            initState(
                !viewModel.isOnline.get(),
                stateData.platformList,
                stateData.aircraftList,
                stateData.platform,
                stateData.aircraftType,
                stateData.aircraftBoardNumber,
                stateData.flightNumber
            )

            replace(containerLayout, true)
            visible()
        }

        actionTaskButton.apply {
            setText(R.string.arrived_parking)
            setOnClickListener {
                disable()
                if (viewModel.isOnline.get()) viewModel.arrivedAtPlatformSetState()
                else viewModel.arrivedAtPlatformSetState(
                    preparationForRefuelingState.currentPlatformId,
                    preparationForRefuelingState.currentAircraftType,
                    preparationForRefuelingState.currentAircraftNumber,
                    preparationForRefuelingState.currentFlightNumber
                )
            }
            enable()
            visible()
        }
    }

    private fun drawArrivedAtPlatformState(stateData: ArrivedAtPlatformState) {
        preparationForRefuelingState.apply {

            initState(
                !viewModel.isOnline.get(),
                stateData.platformList,
                stateData.aircraftList,
                stateData.platform,
                stateData.aircraftType,
                stateData.aircraftBoardNumber,
                stateData.flightNumber
            )

            replace(containerLayout, true)
            visible()
        }

            actionTaskButton.apply {
                setText(R.string.took_position_for_refueling)
                setOnClickListener {
                    disable()
                    if (viewModel.isOnline.get()) viewModel.tookPositionToFuelingSetState()
                    else viewModel.tookPositionToFuelingSetState(
                        preparationForRefuelingState.currentPlatformId,
                        preparationForRefuelingState.currentAircraftType,
                        preparationForRefuelingState.currentAircraftNumber,
                        preparationForRefuelingState.currentFlightNumber
                    )
                }
                enable()
            }
        }

    private fun drawTookPositionForFueling(stateData: TookPositionForFueling) {
        preparationForRefuelingState.apply {

            initState(
                !viewModel.isOnline.get(),
                stateData.platformList,
                stateData.aircraftList,
                stateData.platform,
                stateData.aircraftType,
                stateData.aircraftBoardNumber,
                stateData.flightNumber
            )

            replace(containerLayout, true)
            visible()
        }

        if (stateData.isBlockChain && viewModel.isOnline.get()) {
            actionTaskButton.apply {
                setText(R.string.ready_for_refueling)
                setOnClickListener {
                    disable()
                    viewModel.refuelingRequestSentSetState()
                }

                enable()
            }
        } else {
            actionTaskButton.apply {
                disable()
                background = resources.getDrawable(R.color.lochmara, null)
                setText(R.string.ready_for_refueling)
                setOnClickListener {
                    if (viewModel.isOnline.get()) viewModel.readyForFuelingSetState()
                    else viewModel.readyForFuelingSetState(
                        platformId = preparationForRefuelingState.currentPlatformId,
                        type = preparationForRefuelingState.currentAircraftType,
                        number = preparationForRefuelingState.currentAircraftNumber,
                        flightNumber = preparationForRefuelingState.currentFlightNumber
                    )
                }
                enable()
            }
        }
    }

    private fun drawRefuelingRequestSent(stateData: RefuelingRequestSent) {
        waitingForApproveState.apply {
            replace(containerLayout, true)
            visible()

            setTimer(stateData.requestTime)
        }

        actionTaskButton.apply {
            text = resources.getString(R.string.request_cancelling_button)
            background = resources.getDrawable(R.color.buttercup, null)
            enable()

            setOnClickListener {
                disable()
                viewModel.cancelRefuelingRequest()
            }
        }
    }

    private fun drawReadyForFuellingState(stateData: ReadyForFuellingState) {
        if (stateData.difMass == null) enableRejectButton()
        else disableRejectButton()

        fuelInfoState.apply {

            initFuelState(
                stateData.enableAntiIcing,
                stateData.fuelDensity,
                stateData.fuelBrand,
                stateData.isKilosMeasurement,
                stateData.requestedVolume,
                stateData.requestedMass,
                stateData.difMass,
                stateData.antiIcingBrand
            )

            if (stateData.difMass == null) {
                enableFuelEditText(!stateData.isBlockChain)
            } else {
                enableFuelEditText(false)
            }

            replace(containerLayout, true)
            visible()

        }

        actionTaskButton.apply {
            background = resources.getDrawable(R.color.lochmara, null)
            setText(R.string.started_refueling)
            setOnClickListener {
                disable()

                if (stateData.isBlockChain) {
                    viewModel.fuelingStateSetState()
                } else {
                    val fuelValues = fuelInfoState.getFuelValues()

                    viewModel.fuelingStateSetState(
                        fuelValues.first,
                        fuelValues.second
                    )
                }
            }

            visible()
            enable()
        }
    }

    private fun drawFuelingState(stateData: FuelingState) {
        disableRejectButton()

        fuelInfoState.apply {

            initFuelState(
                stateData.enableAntiIcing,
                stateData.fuelDensity,
                stateData.fuelBrand,
                stateData.isKilosMeasurement,
                stateData.requestedVolume,
                stateData.requestedMass,
                stateData.difMass,
                stateData.antiIcingBrand
            )

            if (stateData.difMass == null) {
                enableFuelEditText(false)
            }

            replace(containerLayout, true)
            visible()


            setState(TaskStateEnum.START_FUELING)

            setSuspendContinueButtonOnClick { _, _ ->

                startActivityForResult(
                    SuspendRefuelingActivity.newInstance(
                        requireContext(),
                        taskId,
                        stateData.isBlockChain
                    ),
                    REQUEST_CODE
                )
            }
        }

        actionTaskButton.apply {
            setText(R.string.terminated_refueling)
            setOnClickListener {
                disable()

                fuelInfoState.hideSuspendingButton(true)

                val fuelValues = fuelInfoState.getFuelValues()

                viewModel.finishedFuelingStateSet(
                    fuelValues.first,
                    fuelValues.second
                )
            }
            enable()
        }
    }

    private fun drawSuspendedFuelingState(stateData: SuspendedFuelingState) {
        disableRejectButton()

        fuelInfoState.apply {

            initFuelState(
                stateData.enableAntiIcing,
                stateData.fuelDensity,
                stateData.fuelBrand,
                stateData.isKilosMeasurement,
                stateData.requestedVolume,
                stateData.requestedMass,
                stateData.difMass,
                stateData.antiIcingBrand
            )

            if (stateData.difMass == null && stateData.canEditFuel) {
                enableFuelEditText(!stateData.isBlockChain)
            } else {
                enableFuelEditText(false)
            }

            replace(containerLayout, true)
            visible()

            setState(TaskStateEnum.PAUSE_FUELING)
            setSuspendContinueButtonOnClick { _, _ ->
                if (stateData.isBlockChain) {
                    viewModel.continuedFuelingStateSet()
                } else {
                    val fuelValues = fuelInfoState.getFuelValues()

                    viewModel.continuedFuelingStateSet(
                        fuelValues.first,
                        fuelValues.second
                    )
                }
            }
        }

        actionTaskButton.apply {
            disable()
            background = resources.getDrawable(R.color.bali_hai, null)
            setText(R.string.terminated_refueling)
        }
    }

    private fun drawContinuedFuelingState(stateData: ContinuedFuelingState) {
        disableRejectButton()

        fuelInfoState.apply {

            initFuelState(
                stateData.enableAntiIcing,
                stateData.fuelDensity,
                stateData.fuelBrand,
                stateData.isKilosMeasurement,
                stateData.requestedVolume,
                stateData.requestedMass,
                stateData.difMass,
                stateData.antiIcingBrand
            )

            if (stateData.difMass == null) {
                enableFuelEditText(false)
            }

            replace(containerLayout, true)
            visible()

            setState(TaskStateEnum.RESUME_FUELING)
            setSuspendContinueButtonOnClick { _, _ ->

                startActivityForResult(
                    SuspendRefuelingActivity.newInstance(
                        requireContext(),
                        taskId,
                        stateData.isBlockChain
                    ),
                    REQUEST_CODE
                )
            }
        }

        actionTaskButton.apply {
            background = resources.getDrawable(R.color.lochmara, null)
            setText(R.string.terminated_refueling)
            setOnClickListener {
                disable()

                fuelInfoState.hideSuspendingButton(true)

                val fuelValues = fuelInfoState.getFuelValues()

                viewModel.finishedFuelingStateSet(
                    fuelValues.first,
                    fuelValues.second
                )
            }
            enable()
        }
    }

    private fun drawFinishedFuelingState(stateData: FinishedFuelingState) {
        disableRejectButton()

        receiptInfoInputState.apply {

            initState(stateData.deliveryReceiptNumber,
                stateData.fuelDensity,
                stateData.isAntiIcing,
                stateData.isKilosMeasurement,
                stateData.shiftCounter,
                stateData.antiIcingPercentage,
                stateData.antiIcingDensity)

            withdrawalOnTextChangeDisposable.dispose()
            fuelingTotalRecountDisposable.dispose()

            withdrawalOnTextChangeDisposable =
                isNotEmptyFieldsObservable.subscribe(this@AircraftFuellingTaskFragment::isActionButtonEnable)
            fuelingTotalRecountDisposable =
                fuelingTotalValueObservable.subscribe()

            replace(containerLayout, true)

            visible()

            setFocusOnEditText()
        }

        actionTaskButton.apply {
            visible()
            setText(R.string.ahead)
            setOnClickListener {
                disable()

                if (stateData.isBlockChain && viewModel.isOnline.get()) {
                    viewModel.receiptApproveRequestedStateSet(
                        receiptInfoInputState.deliveryReceiptNumber,
                        receiptInfoInputState.refuelingFuelValue,
                        receiptInfoInputState.fuelMass,
                        receiptInfoInputState.currentCounterValue,
                        receiptInfoInputState.antiIcingValue,
                        receiptInfoInputState.antiIcingMass
                    )
                } else {
                    viewModel.deliveryReceiptCreatedStateSet(
                        receiptInfoInputState.deliveryReceiptNumber,
                        receiptInfoInputState.refuelingFuelValue,
                        receiptInfoInputState.fuelMass,
                        receiptInfoInputState.currentCounterValue,
                        receiptInfoInputState.antiIcingValue,
                        receiptInfoInputState.antiIcingMass
                    )
                }
            }
            enable()
        }
    }

    private fun drawDeliveryReceiptCreatedState(stateData: DeliveryReceiptCreatedState) {
        disableRejectButton()

        receiptInfoCheckingState.apply {
            initState(
                stateData.controlTicketNumber,
                stateData.fuelBrand,
                stateData.fuelTemperature,
                stateData.fuelDensity,
                stateData.antiIcingDensity,
                stateData.antiIcingPercentage,
                stateData.shiftCounter,
                stateData.filledFuelVolume,
                stateData.filledFuelMass,
                stateData.enableAntiIcing,
                stateData.isKilosMeasurement,
                stateData.filledAntiIcingVolume,
                stateData.filledAntiIcingMass
            )

            changeForBlockChain(stateData.isBlockChain)

            deliveryReceiptOnDataChangeDisposable =
                onDataChangeClick.subscribe(this@AircraftFuellingTaskFragment::backToDataChanging)

            replace(containerLayout, true)
            visible()
        }

        actionTaskButton.apply {
            background = resources.getDrawable(R.color.lochmara, null)
            setText(R.string.save_delivery_receipt)
            setOnClickListener {
                disable()
                viewModel.deliveryReceiptConfirmedStateSet(
                    receiptInfoCheckingState.currentCounterValue
                )
            }

            visible()
            enable()
        }
    }

    private fun drawReceiptApproveRequestedState(stateData: ReceiptApproveRequestedState) {
        disableRejectButton()

        waitingForApproveState.apply {

            setTimer(stateData.requestTime)
            replace(containerLayout, true)
            visible()
        }

        actionTaskButton.apply {
            text = resources.getString(R.string.request_cancelling_button)
            background = resources.getDrawable(R.color.buttercup, null)
            enable()

            setOnClickListener {
                disable()
                viewModel.cancelReceiptApproveRequest()
            }
        }
    }

    private fun drawAdditionalFuelingRequiredState(stateData: AdditionalFuelingRequiredState) {
        disableRejectButton()

        additionalRefuelingState.apply {

            initState(
                stateData.isAntiIcing,
                stateData.isKilosMeasurement,
                stateData.filledVolume,
                stateData.filledMass,
                stateData.requestedVolume,
                stateData.requestedMass,
                stateData.antiIcingMass,
                stateData.antiIcingVolume,
                stateData.fuelDensity
            )

            replace(containerLayout, true)
            visible()

        }

        actionTaskButton.apply {
            background = resources.getDrawable(R.color.lochmara, null)
            visible()
            text = "Понятно - продолжить заправку ВС"
            setOnClickListener {
                disable()
                viewModel.readyForFuelingSetState(true)
            }
            enable()
        }
    }

    private fun drawDeliveryReceiptConfirmedState(stateData: DeliveryReceiptConfirmedState) {
        disableRejectButton()

        receiptPrintingState.apply {

            initState(
                stateData.enableAntiIcing,
                stateData.isKilosMeasurement,
                stateData.controlTicketNumber,
                stateData.fuelBrand,
                stateData.fuelTemperature,
                stateData.fuelDensity,
                stateData.antiIcingPercentage,
                stateData.antiIcingDensity,
                stateData.shiftCounter,
                stateData.filledVolume,
                stateData.filledMass,
                stateData.antiIcingVolume,
                stateData.antiIcingMass
            )

            setPrintButtonOnClick {
                Toast.makeText(requireContext(), "В разработке", Toast.LENGTH_SHORT).show()
            }

            replace(containerLayout, true)
            visible()
        }

        actionTaskButton.apply {
            background = resources.getDrawable(R.color.lochmara, null)
            setText(R.string.task_done)
            setOnClickListener {
                disable()
                viewModel.finishedFuelingTaskStateSet()
            }
            enable()
        }
    }

    private fun drawDeliveryReceiptCorrectionState(stateData: DeliveryReceiptCorrectionState) {

        disableRejectButton()

        actionTaskButton.gone()

        receiptCorrectionState.apply {
            initState(stateData.correctionText)

            deliveryReceiptCorrectionDisposable = onDataChangeClick.subscribe(this@AircraftFuellingTaskFragment::backToDataChanging)

            replace(containerLayout)

            visible()
        }
    }

    private fun drawFinishedFuellingTaskState(stateData: FinishedFuellingTaskState) {
        disableRejectButton()

        taskCompletionState.apply {

            initState(
                stateData.isAntiIcingEnabled,
                stateData.isKilosMeasurement,
                stateData.planStartTime,
                stateData.planFinishDateTime,
                stateData.factStartTime ?: OffsetDateTime.now(),
                stateData.factFinishDateTime ?: OffsetDateTime.now(),
                stateData.filledVolume,
                stateData.filledMass,
                stateData.filledAntiIcingVolume,
                stateData.filledAntiIcingMass
            )

            replace(containerLayout, true)
            visible()
        }

        actionTaskButton.apply {
            setText(R.string.left_service_area)
            setOnClickListener {
                disable()
                viewModel.leftPlatformStateSet()
            }

            enable()
        }
    }

    private fun drawLeftPlatformState() {
        if (triggeredExit) return

        triggeredExit = true

        val intent = MainActivity.newIntent(requireContext()).addClearStackFlags()
        startActivity(intent)
    }


    private fun initTaskData(state: AircraftTaskInitialState) {

        headerCallback?.updateHeader(state.taskNumber)

        fullTimeTextView.text = getString(
            R.string.task_start_end_time,
            state.planStartTime.simpleTimeFormat,
            state.planFinishDateTime.simpleTimeFormat
        )

        taskFactStartTime = state.factStartTime

        taskChronometer.text = getElapsedTaskTimeFormatString()

        taskChronometer.apply {
            onChronometerTickListener = this@AircraftFuellingTaskFragment
            start()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()

        clearResources()
    }


    override fun onDestroy() {
        super.onDestroy()

        clearResources()
    }

    private fun clearResources() {
        withdrawalOnTextChangeDisposable.dispose()
        fuelingTotalRecountDisposable.dispose()

        taskStepsLinearLayout.removeAllViews()
        containerLayout.removeAllViews()

        disposables.clear()

//        viewModel.onDestroyViewState()
    }

    companion object {

        @JvmStatic
        fun newInstance(taskId: UUID) =
            AircraftFuellingTaskFragment().apply {
                arguments = Bundle().apply {
                    putSerializable(TASK_ID, taskId)
                }
            }
    }

    private fun isActionButtonEnable(isEnable: Boolean) {
        if (isEnable) {
            actionTaskButton.apply {
                enable()
                background = resources.getDrawable(R.color.lochmara, null)
            }
        } else {
            actionTaskButton.apply {
                disable()
                background = resources.getDrawable(R.color.bali_hai, null)
            }
        }
    }

    @Suppress("UNUSED_PARAMETER")
    private fun backToDataChanging(t: Unit) {
        viewModel.finishedFuelingStateSet(null, null, true)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode != REQUEST_CODE) return

        if (resultCode == Activity.RESULT_OK) {
            viewModel.suspendedFuelingStateSet(
                data?.getBooleanExtra(
                    SuspendRefuelingActivity.CAN_EDIT_FUEL,
                    true
                ) ?: true
            )
        }
    }

    override fun onChronometerTick(chronometer: Chronometer?) {
        if (chronometer == null) return

        chronometer.text = getElapsedTaskTimeFormatString()
    }

    private fun getElapsedTaskTimeFormatString(): String? = taskFactStartTime?.run {
        Duration.between(this, LocalDateTime.now()).run {
            LocalTime.ofSecondOfDay(this.seconds).fullTimeFormat
        }
    }

    private fun enableRejectButton() {
        rejectButton.visible()
        rejectButton.setOnClickListener {
            startActivity(CancelTaskActivity.newInstance(requireContext(), taskId))
        }
    }

    private fun disableRejectButton() {
        rejectButton.gone()
    }

    private fun createNoConnectionDialog(state: LostConnectionStates): AlertDialog {

        val message = when (state) {

            LostConnectionStates.DR_APPROVING_LOST -> resources.getString(R.string.no_con_alert_approving_dr)
            LostConnectionStates.REFUELING_CHANGES_LOST -> resources.getString(R.string.no_con_alert_refueling)
        }

        val builder = AlertDialog.Builder(requireContext(), R.style.AlertDialogCustom)
            .setTitle(resources.getString(R.string.no_con_dialog_alert_title))
            .setMessage(message)
            .setCancelable(false)
            .setPositiveButton("Ok") { dialog, _ ->
                viewModel.userShowWarningNotification()
                dialog.cancel()
            }

        return builder.create()
    }
}
