package com.malmstein.hnews.stories;

import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.malmstein.hnews.BuildConfig;
import com.malmstein.hnews.R;
import com.malmstein.hnews.base.DeveloperError;
import com.malmstein.hnews.data.HNewsContract;

import static com.malmstein.hnews.data.HNewsContract.STORY_COLUMNS;

public class ArticleFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    public static final String ARG_STORY_ID = BuildConfig.APPLICATION_ID + ".ARG_STORY_ID";
    private static final int ARTICLE_LOADER = 0;
    private WebView webView;

    public static ArticleFragment from(Long itemId){
        Bundle args = new Bundle();
        args.putSerializable(ARG_STORY_ID, itemId);
        ArticleFragment fragment = new ArticleFragment();
        fragment.setArguments(args);
        return fragment;
    }

    private Long getItemId(){
        if (getArguments().containsKey(ARG_STORY_ID)){
            return getArguments().getLong(ARG_STORY_ID);
        } else {
            throw new DeveloperError("Missing argument");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_article, container, false);

        webView = (WebView) rootView.findViewById(R.id.article_webview);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new HackerNewsWebClient());

        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        Bundle arguments = getArguments();
        if (arguments != null && arguments.containsKey(ARG_STORY_ID)) {
            getLoaderManager().restartLoader(ARTICLE_LOADER, null, this);
        }
    }

    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        Uri storyUri = HNewsContract.ItemEntry.buildItemUri(getItemId());

        return new CursorLoader(
                getActivity(),
                storyUri,
                STORY_COLUMNS,
                null,
                null,
                null
        );
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        if (data != null && data.moveToFirst()) {
            String url = data.getString(data.getColumnIndex(HNewsContract.ItemEntry.COLUMN_URL));
            webView.loadUrl(url);
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {

    }

    private class HackerNewsWebClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
//            if (Uri.parse(url).getHost().equals("www.example.com")) {
//                // This is my web site, so do not override; let my WebView load the page
//                return false;
//            }
//            // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
//            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//            startActivity(intent);
//            return true;
        }
    }
}

@@ -50,23 +50,86 @@
 oid.
-database.Cursor
+content.Intent;%0Aimport android.database.Cursor;%0Aimport android.graphics.Bitmap
 ;%0Aim
@@ -1147,16 +1147,17 @@
  itemId)
+ 
 %7B%0A      
@@ -1393,16 +1393,17 @@
 ItemId()
+ 
 %7B%0A      
@@ -1449,16 +1449,17 @@
 ORY_ID))
+ 
 %7B%0A      
@@ -2006,16 +2006,113 @@
 (true);%0A
+        webSettings.setUseWideViewPort(true);%0A        webSettings.setLoadWithOverviewMode(true);%0A
         
@@ -3254,293 +3254,570 @@
 t %7B%0A
-        @Override%0A        public boolean shouldOverrideUrlLoading(WebView view, String url) %7B%0A            return false;%0A//            if (Uri.parse(url).getHost().equals(%22www.example.com%22)) %7B%0A//                // This is my web site, so do not override; let my WebView load the page%0A//
+%0A        boolean loadedFinished = false;%0A%0A        @Override%0A        public void onPageFinished(WebView view, String url) %7B%0A            loadedFinished = true;%0A        %7D%0A%0A        @Override%0A        public void onPageStarted(WebView view, String url, Bitmap favicon) %7B%0A            if (loadedFinished) %7B%0A                launchExternalBrowser(Uri.parse(url));%0A            %7D%0A        %7D%0A%0A        @Override%0A        public boolean shouldOverrideUrlLoading(WebView view, String url) %7B%0A            if (loadedFinished) %7B%0A                launchExternalBrowser(Uri.parse(url));%0A
     
@@ -3839,17 +3839,14 @@
 urn 
-fals
+tru
 e;%0A
-//
     
@@ -3855,19 +3855,17 @@
       %7D%0A
-// 
+%0A
         
@@ -3871,108 +3871,91 @@
     
-// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs%0A//
+ return false;%0A        %7D%0A%0A        private void launchExternalBrowser(Uri newUri) %7B%0A
     
@@ -4013,27 +4013,17 @@
 EW, 
+new
 Uri
-.parse(url)
 );%0A
-//
     
@@ -4057,10 +4057,8 @@
 t);%0A
-//
     
@@ -4061,35 +4061,46 @@
             
-return true
+getActivity().finish()
 ;%0A        %7D%0A

handle the url loading correctly