/*
 * /////////////////////////////////////////////////////////////////////////////////
 * //
 * // Copyright <2015>-<2016> Avaya Inc. All Rights Reserved.
 * //
 * // Usage of this source is bound to the terms described
 * // in assets/Licence.txt
 * //
 * // Avaya - Confidential & Proprietary. Use pursuant to your signed agreement
 * // or Avaya Policy
 * //
 * /////////////////////////////////////////////////////////////////////////////
 */

package com.avaya.odonnell3.AndroidChatTemplate_2_3.fragments;


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;

import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.avaya.odonnell3.AndroidChatTemplate_2_3.R;
import com.avaya.odonnell3.AndroidChatTemplate_2_3.classes.CoBrowseJSInterface;

public class CoBrowseFragment extends Fragment implements View.OnTouchListener {

    public final String className = this.getClass().getSimpleName();
    public WebView webView;
    Bundle b;
    private String url;
    Context context;
    public View rootView;
    CoBrowseHandler callBack;
    public LinearLayout agentChatWindow;
    private int _xDelta;
    private int _yDelta;
    public ViewGroup rootLayout;


    public CoBrowseFragment() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.v("Info",className+"  onCreateView()");

        rootView = inflater.inflate(R.layout.fragment_co_browse, container, false);
        rootLayout = (ViewGroup) rootView.findViewById(R.id.co_browse_fragment_root);
        context = rootView.getContext();
        webView = (WebView) rootView.findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.clearCache(true);
        webView.getSettings().setAppCacheMaxSize( 10 * 1024 * 1024 ); // 10MB
        webView.getSettings().setAppCachePath(context.getApplicationContext().getCacheDir().getAbsolutePath() );
        webView.getSettings().setAllowFileAccess( true );
        webView.getSettings().setAppCacheEnabled( true );
        webView.getSettings().setJavaScriptEnabled( true );
        webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onConsoleMessage(String message, int lineNumber, String sourceID) {
                Log.v("Console", "Line No: |" + lineNumber + " Message: |" + message + " Source: " + sourceID);
            }
        });
        webView.setWebViewClient(new WebViewClient() {
                                     @Override
                                     public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                                         super.onReceivedError(view, request, error);
                                         Log.v("Error", "WebView Error: Request: " + request + " Error: " + error);
                                     }
                                 }
        );

        webView.addJavascriptInterface(new CoBrowseJSInterface(this.getActivity()), "Android");
        LayoutInflater missedMessageLayout = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        agentChatWindow = (LinearLayout) missedMessageLayout.inflate(R.layout.layout_cobrowse_floating, null);
        agentChatWindow.setOnTouchListener(this);
        return rootView;

    }

    @Override
    public void onPause() {
        super.onPause();
        Log.v("Info",className+"  onPause()");
        b = new Bundle();
        b.putString("url", url);
        //  webView.saveState(b);
        Log.v("Info,", "saving URL: " + url);
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.v("Info",className+"  onResume()");
        if (b != null) {
            String temp = b.getString("url");
            Log.v("Info,", "onPause() retrieve URL: " + temp);
            //  webView.loadUrl(temp);
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        Log.v("Info",className+"  onSaveInstanceState()");
        super.onSaveInstanceState(outState);
        webView.saveState(outState);
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.v("Info",className+"  onAttach()");
        callBack = (CoBrowseHandler) activity;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.v("Info",className+"  onActivityCreated()");
        super.onActivityCreated(savedInstanceState);
        webView.restoreState(savedInstanceState);
    }

    public void setUrl(String url) {
        Log.v("Info",className+"  setUrl()");

        this.url = url;
    }

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        Log.v("Info",className+"  onTouch()");
        return makeAgentWindowDraggable(view, event);
    }


    //allows the agent window in co-browse to be dragged around the screen
    private boolean makeAgentWindowDraggable(View view, MotionEvent event) {
        Log.v("Info",className+" makeAgentWindowDraggable()");
        final int X = (int) event.getRawX();
        final int Y = (int) event.getRawY();
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_DOWN:
                RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                _xDelta = X - lParams.leftMargin;
                _yDelta = Y - lParams.topMargin;
                break;
            case MotionEvent.ACTION_UP:
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                break;
            case MotionEvent.ACTION_POINTER_UP:
                break;
            case MotionEvent.ACTION_MOVE:
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view
                        .getLayoutParams();
                layoutParams.leftMargin = X - _xDelta;
                layoutParams.topMargin = Y - _yDelta;
                layoutParams.rightMargin = -250;
                layoutParams.bottomMargin = -250;
                view.setLayoutParams(layoutParams);
                break;
        }
        rootLayout.invalidate();
        return true;
    }


    public interface CoBrowseHandler {
        void setCoBrowseMessage(String message);
    }


}