/*
 * ********************************************************************************************************************
 *
 *               iFHS7.
 *              ;BBMBMBMc                  rZMBMBR              BMB
 *              MBEr:;PBM,               7MBMMEOBB:             BBB                       RBW
 *     XK:      BO     SB.     :SZ       MBM.       c;;     ir  BBM :FFr       :SSF:    ;xBMB:r   iuGXv.    i:. iF2;
 *     DBBM0r.  :D     S7   ;XMBMB       GMBMu.     MBM:   BMB  MBMBBBMBMS   WMBMBMBBK  MBMBMBM  BMBRBMBW  .MBMBMBMBB
 *      :JMRMMD  ..    ,  1MMRM1;         ;MBMBBR:   MBM  ;MB:  BMB:   MBM. RMBr   sBMH   BM0         UMB,  BMB.  KMBv
 *     ;.   XOW  B1; :uM: 1RE,   i           .2BMBs  rMB. MBO   MBO    JMB; MBB     MBM   BBS    7MBMBOBM:  MBW   :BMc
 *     OBRJ.SEE  MRDOWOR, 3DE:7OBM       .     ;BMB   RMR7BM    BMB    MBB. BMB    ,BMR  .BBZ   MMB   rMB,  BMM   rMB7
 *     :FBRO0D0  RKXSXPR. JOKOOMPi       BMBSSWBMB;    BMBB:    MBMB0ZMBMS  .BMBOXRBMB    MBMDE RBM2;SMBM;  MBB   xBM2
 *         iZGE  O0SHSPO. uGZ7.          sBMBMBDL      :BMO     OZu:BMBK,     rRBMB0;     ,EBMB  xBMBr:ER.  RDU   :OO;
 *     ,BZ, 1D0  RPSFHXR. xWZ .SMr                  . .BBB
 *      :0BMRDG  RESSSKR. 2WOMBW;                   BMBMR
 *         i0BM: SWKHKGO  MBDv
 *           .UB  OOGDM. MK,                                          Copyright (c) 2015-2019.  斯伯坦机器人
 *              ,  XMW  ..
 *                  r                                                                     All rights reserved.
 *
 * ********************************************************************************************************************
 */

package com.sybotan.android.views.webview

import android.util.Log
import android.webkit.*
import com.sybotan.android.base.utils.SQrCodeUtil
import android.graphics.Bitmap
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import android.net.Uri
import com.sybotan.android.base.extensions.param


/**
 * @author  庞利祥(sybotan@126.com)
 */
open class SWebViewClient : WebViewClient() {
    /**
     * 类对象
     */
    companion object {
        private val TAG = SWebViewClient::class.java.name
        private const val serviceName = "services"
    } // companion object

    /**
     * 页面开始加载 可以设置加载进度条
     *
     * @param   view        webview控件
     * @param   url         url地址
     * @param   favicon     页面图标
     */
    override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
        return
    } // Function onPageStarted()

    override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
        Log.d(TAG, "shouldInterceptRequest===${request.url}")
        val url = request.url.toString()
        Log.e(TAG, "url1=$url")
//        if (url.startsWith("http://android/")) {
//            return assetsRequest(view, request)
//        } else if (url.startsWith("$serviceName://")) {
//            return servicesRequest(view, request)
//        }

//        if (url =="http://172.16.3.12:8080/dist/") {
//            Log.d(TAG, "res_vue==dist/${url.substring(28)}")
//            val input = view.context.assets.open("dist/index.html")
//            return WebResourceResponse("text/html", "UTF-8", input)
//        }
//
//        if (url.startsWith("http://172.16.3.12:8080/dist/")) {
//            Log.d(TAG, "res==dist/${url.substring(29)}")
//            val input = view.context.assets.open("dist/${url.substring(29)}")
//
//            return if (url.endsWith(".css"))
//                WebResourceResponse("text/css", "UTF-8", input)
//            else {
//                Log.d(TAG, "----------------------------------------------")
//                WebResourceResponse("application/x-javascript", "UTF-8", input)
//            }
//        }

        return super.shouldInterceptRequest(view, request)
    } // Function shouldInterceptRequest()

    /**
     * url请求二维码
     *
     * @param   request     url请求
     * @return  应答信息
     */
    private fun assetsRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
        val url = request.url.toString()

        Log.e(TAG, "urlhead=${url.substring(15)}")
        val input = view.context.assets.open("/vue/${url.substring(14)}")

        return when {
            url.endsWith(".css") -> WebResourceResponse("text/css", "UTF-8", input)
            url.endsWith(".html") -> WebResourceResponse("text/html", "UTF-8", input)
            else -> {
                Log.d(TAG, "----------------------------------------------")
                WebResourceResponse("application/x-javascript", "UTF-8", input)
            }
        }
    } // Function urlRequest()

    /**
     * services请求
     *
     * @param   request     url请求
     * @return  应答信息
     */
    private fun servicesRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
        val url = request.url.toString()
        if (url.startsWith("$serviceName://qrcode")) {
            return servicesQrCodeRequest(view, request)
        }
        return null
    } // Function urlRequest()

    /**
     * services二维码请求
     *e
     * @param   request     url请求
     * @return  应答信息
     */
    private fun servicesQrCodeRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
        val url = request.url.toString()

        val context = Uri.decode(request.param("context"))
        var size = 200
        try {           // 防止解析出错
            size = request.param("size").toInt()
        } catch (e: Exception) {
            // DO NOTHING
        }


        val qrcode = SQrCodeUtil.createQrCode(context, size)
        val bmpOutput = ByteArrayOutputStream()
        qrcode!!.compress(Bitmap.CompressFormat.PNG, 100, bmpOutput)
        val qrcodeInput = ByteArrayInputStream(bmpOutput.toByteArray())
        return WebResourceResponse("image/png", "UTF-8", qrcodeInput)
    } // Function urlRequest()
//
//    /*页面加载结束，可以设置进度条状态*/
//    override fun onPageFinished(view: WebView?, url: String?) {
//
//    } // Function onPageFinished()
//
//    /*加载主机指定的url中的资源*/
//    override fun onLoadResource(view: WebView?, url: String?) {
//
//    } // Function onLoadResource()
//
//    /*加载页面的服务器出现错误时候调用*/
//    override fun onReceivedError(view: WebView?, request: WebResourceRequest?, error: WebResourceError?) {
//
//    } // Function onReceivedError()
//
//    /*webview加载https请求时报错*/
//    override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
//
//        /*继续挂载请求,等待响应*/
//        handler!!.proceed()
//
//        /*取消挂载请求*/
//        //handler.cancel()
//
//        /*发送消息，做其他处理*/
//        //handler.handleMessage(null)
//    } // Function onReceivedSslError()
} // Class SWebViewClient