package com.autotech.we1l.fragments

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.CoordinatorLayout
import android.support.v4.content.ContextCompat
import android.support.v4.view.GravityCompat
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.Toast
import com.android.volley.VolleyError
import com.autotech.we1l.R
import com.autotech.we1l.activities.PlaceHolderActivity
import com.autotech.we1l.adapters.ColorImagesAdapter
import com.autotech.we1l.adapters.ImageSliderAdapter
import com.autotech.we1l.adapters.TodayTrendingAdapter
import com.autotech.we1l.app.AppLanguage
import com.autotech.we1l.app.User
import com.autotech.we1l.fragments.dialog_fragments.ProductAmountDialogFragment
import com.autotech.we1l.items.ColorImage
import com.autotech.we1l.items.Image
import com.autotech.we1l.items.Product
import com.autotech.we1l.items.TodayTrending
import com.autotech.we1l.my_classes.BaseAdapter
import com.autotech.we1l.my_classes.BaseFragment
import com.autotech.we1l.my_classes.BaseList
import com.autotech.we1l.tools.*
import com.autotech.we1l.volley.IVolleyRequest
import com.autotech.we1l.volley.VolleyRequest
import kotlinx.android.synthetic.main.fragment_product.*
import org.json.JSONObject
import java.util.*
import kotlin.collections.ArrayList


class ProductDetailsFragment : BaseFragment() {

    private lateinit var product: Product
    private lateinit var productId: String
    private var colorId = 0
    private val todayTrendingList = ArrayList<TodayTrending>()

    lateinit var imageSliderAdapter: ImageSliderAdapter
    private lateinit var colorImagesAdapter: ColorImagesAdapter

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        rootView = inflater.inflate(R.layout.fragment_product, container, false)

        productId = arguments!!.getString(ATTR_PRODUCT)!!
        return rootView
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)


        val lp: CoordinatorLayout.LayoutParams = fab_cart.layoutParams as CoordinatorLayout.LayoutParams
        if (User.getUserLanguage(context!!) == "ar")
            lp.anchorGravity = Gravity.BOTTOM or GravityCompat.START

        fab_cart.layoutParams = lp

        getData()
    }

    private fun getData() {
        hideAll()

        val inputMap = HashMap<String, String>()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_ID] = productId
        inputMap[ATTR_CURRENCY] = User.loadVisibleCurrency(context!!)?.id.toString()
        inputMap[ATTR_CUSTOMER] = User.instance?.id.toString()
        inputMap[ATTR_LANGUAGE] = User.getUserLanguageId(context!!)!!.toString()

        VolleyRequest.getInstance().post(REQUEST_GET_PRODUCT, inputMap, object : IVolleyRequest {
            override fun onFail(errorListener: VolleyError?) {
                Toast.makeText(context, errorListener?.message, Toast.LENGTH_SHORT).show()
            }

            override fun onSuccess(response: JSONObject?) {

                if (response!!.getInt(ATTR_ERROR_CODE) != CODE_OK) {
                    Toast.makeText(context, response.getString(ATTR_ERROR_MESSAGE), Toast.LENGTH_SHORT).show()
                    return
                }

                val jsonObject: JSONObject = response.getJSONObject(ATTR_DATA).getJSONObject(ATTR_DATA)

                product = Product(jsonObject, jsonObject.getInt("CategoryID"))

                for (i in 0 until jsonObject.getJSONArray("FromSameCategory").length()) {
                    val sameCategoryProduct = TodayTrending(jsonObject.getJSONArray("FromSameCategory").getJSONObject(i).getInt("ID")
                            , jsonObject.getJSONArray("FromSameCategory").getJSONObject(i).getString("Name"),
                            jsonObject.getJSONArray("FromSameCategory").getJSONObject(i).getString("BrandName")
                            , jsonObject.getJSONArray("FromSameCategory").getJSONObject(i).getJSONArray("Images").getString(0),
                            jsonObject.getJSONArray("FromSameCategory").getJSONObject(i).getBoolean("IsLiked"))

                    todayTrendingList.add(sameCategoryProduct)
                }

                showAll()
            }
        }).apply { requestsArray.add(this) }
    }

    @SuppressLint("SetTextI18n")
    override fun setupViews() {
        text_view_more_from.text=AppLanguage.getString(Language.txt_v_more_from)
    }

    private fun bindView() {

        imageViewFavorite.setOnClickListener {

            if (!User.isValid()) {
                Toast.makeText(context, AppLanguage.getString(Language.prompt_not_logged_in), Toast.LENGTH_LONG).show()
                return@setOnClickListener
            }

            if (product.isInWishList) {
                imageViewFavorite.setImageDrawable(ContextCompat.getDrawable(context!!, R.drawable.ic_bottom_favorite_inactive))
                imageViewFavorite.startAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in))
                removeFromWishList(product)
            } else {
                imageViewFavorite.setImageDrawable(ContextCompat.getDrawable(context!!, R.drawable.ic_favorite_red))
                imageViewFavorite.startAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in))
                addToWishList(product)
            }
        }

        (activity as PlaceHolderActivity).toolbarView.visibility = View.GONE

        imageViewClose.setOnClickListener { (activity as PlaceHolderActivity).finish() }

        imageViewShare.setOnClickListener {
            val share = Intent()

            share.action = Intent.ACTION_SEND
            share.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            share.type = "text/plain"
            share.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share))
            share.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_item, product.name, productId))

            startActivity(Intent.createChooser(share, getString(R.string.share)))
        }

        if (product.colors?.isEmpty()!!)
            recyclerViewColor.visibility = View.GONE

        textViewItemName.text = product.name
        textViewItemBrand.text = product.brandName
        textViewItemContent.text = product.content

        if (product.isInWishList)
            imageViewFavorite.setImageDrawable(ContextCompat.getDrawable(context!!, R.drawable.ic_favorite_red))
        else imageViewFavorite.setImageDrawable(ContextCompat.getDrawable(context!!, R.drawable.ic_bottom_favorite_inactive))


        colorImagesAdapter = ColorImagesAdapter(context!!, product.colors!!
                , object : BaseAdapter.OnClickListener<ColorImage> {
            override fun onClick(holder: RecyclerView.ViewHolder, position: Int, colorImage: ColorImage) {
                colorId = colorImage.id!!
                val list = BaseList<Image>().apply {
                    colorImage.productImages.forEachIndexed { _, s ->
                        add(Image(s))
                    }
                }

                if (list.isEmpty()) return

                imageSliderAdapter = ImageSliderAdapter(context, list)
                viewPager.adapter = imageSliderAdapter
            }
        })

        Tools.setupRVHorizontal(recyclerViewColor, colorImagesAdapter)

        imageSliderAdapter = ImageSliderAdapter(context, BaseList<Image>().apply {
            product.noColor.productImages.forEachIndexed { _, s ->
                add(Image(s))
            }
        })

        viewPager.setPageTransformer(true, ParallaxPageTransformer())
        circleIndicator.setViewPager(viewPager)
        viewPager.adapter = imageSliderAdapter

        textViewItemPrice.text = "${product.price} ${User.loadVisibleCurrency(context!!)!!.name}"

        recyclerViewAlsoLike.layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        recyclerViewAlsoLike.setHasFixedSize(true)
        recyclerViewAlsoLike.adapter = TodayTrendingAdapter(todayTrendingList, context!!, object : TodayTrendingAdapter.ITodayTrendingAdapter {
            override fun onClickTodayTrending(todayTrending: TodayTrending) {
                launchProductDetails(context!!, todayTrending.productID.toString())
            }
        })
    }

    override fun setupClickListeners() {

        fab_cart.setOnClickListener {
            val productAmountDialogFragment = ProductAmountDialogFragment()
            productAmountDialogFragment.arguments = Bundle().apply {
                putSerializable(ATTR_PRODUCT, product)
                putSerializable("COLOR_ITEM", product.colors)
                putInt(ATTR_COLOR_ID, colorId)
            }
            productAmountDialogFragment.show(childFragmentManager, "ProductAmountDialogFragment")
        }
    }

    private fun addToWishList(product: Product) {
        val inputMap = HashMap<String, String>()

        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_PRODUCT] = product.id.toString()
        inputMap[ATTR_CUSTOMER] = User.instance!!.id.toString()

        if (!isNetworkAvailable(context!!)) {
            Toast.makeText(context, AppLanguage.getString(Language.err_no_internet_connection), Toast.LENGTH_LONG).show()
            return
        }

        VolleyRequest.getInstance().post(REQUEST_ADD_TO_WISH_LIST, inputMap, object : IVolleyRequest {

            override fun onSuccess(response: JSONObject?) {
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {
                        product.isInWishList = true
                    }
                }
            }

            override fun onFail(error: VolleyError) {
                Toast.makeText(context, AppLanguage.getString(Language.err_server_connection_error), Toast.LENGTH_LONG).show()
                product.isInWishList = false
                imageViewFavorite.setImageDrawable(ContextCompat.getDrawable(context!!, R.drawable.ic_bottom_favorite_inactive))
                imageViewFavorite.startAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in))
            }

        }).apply { requestsArray.add(this) }
    }

    private fun removeFromWishList(product: Product) {
        val inputMap = HashMap<String, String>()
        inputMap[ATTR_SYSTEM_PASSCODE] = SYSTEM_PASSCODE
        inputMap[ATTR_CUSTOMER] = User.instance!!.id.toString()
        inputMap[ATTR_PRODUCT] = product.id.toString()

        if (!isNetworkAvailable(context!!)) {
            Toast.makeText(context, AppLanguage.getString(Language.err_no_internet_connection), Toast.LENGTH_LONG).show()
            return
        }

        VolleyRequest.getInstance().post(REQUEST_DELETE_FROM_WISH_LIST, inputMap, object : IVolleyRequest {

            override fun onSuccess(response: JSONObject?) {
                when (response!!.getInt(ATTR_ERROR_CODE)) {
                    CODE_OK -> {
                        product.isInWishList = false
                    }
                }
            }

            override fun onFail(error: VolleyError) {
                Toast.makeText(context, AppLanguage.getString(Language.err_server_connection_error), Toast.LENGTH_LONG).show()
                product.isInWishList = true
                imageViewFavorite.setImageDrawable(ContextCompat.getDrawable(context!!, R.drawable.ic_favorite_red))
                imageViewFavorite.startAnimation(AnimationUtils.loadAnimation(context, android.R.anim.fade_in))
            }

        }).apply { requestsArray.add(this) }

    }

    @SuppressLint("RestrictedApi")
    private fun hideAll() {
        progress_bar.visibility = View.VISIBLE

        fab_cart.visibility = View.GONE
        app_bar_layout.visibility = View.GONE
        nested_scroll_view.visibility = View.GONE
    }

    @SuppressLint("RestrictedApi")
    private fun showAll() {
        progress_bar.visibility = View.GONE

        fab_cart.visibility = View.VISIBLE
        app_bar_layout.visibility = View.VISIBLE
        nested_scroll_view.visibility = View.VISIBLE

        bindView()
    }

    override fun crucialRequests() {}
}