/*
 * Copyright (C) 2014 uPhyca Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.uphyca.idobata.android;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.net.CookieHandler;

/**
 * @author Sosuke Masui (masui@uphyca.com)
 */
public class MainActivity extends ActionBarActivity {

    private WebView mWebView;

    private CookieHandler mCookieHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        mCookieHandler = new CookieHandlerAdapter();
        mWebView = new WebView(this);
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setPluginState(WebSettings.PluginState.ON);
        settings.setBuiltInZoomControls(true);
        settings.setAppCacheEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse(url);
                if (uri.getHost()
                       .equals("idobata.io")) {
                    view.loadUrl(url);
                    return true;
                }
                startActivity(new Intent(Intent.ACTION_VIEW, uri));
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                setSupportProgressBarIndeterminateVisibility(true);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                setSupportProgressBarIndeterminateVisibility(false);
                startService(new Intent(MainActivity.this, IdobataService.class));
            }
        });

        setContentView(mWebView);
        mWebView.loadUrl("https://idobata.io/");
    }

    @Override
    protected void onResume() {
        super.onResume();
        CookieSyncManager.getInstance()
                         .stopSync();
    }

    @Override
    protected void onPause() {
        CookieSyncManager.getInstance()
                         .sync();
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return;
        }
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

@@ -918,16 +918,59 @@
 anager;%0A
+import android.webkit.JavascriptInterface;%0A
 import a
@@ -1068,38 +1068,35 @@
 nt;%0A
-%0A
 import 
-java.net.CookieHandler
+android.widget.Toast
 ;%0A%0A/
@@ -1216,67 +1216,78 @@
 ate 
-WebView mWebView;%0A%0A    private CookieHandler mCookieHandler
+static final int READ_REQUEST_CODE = 42;%0A%0A    private WebView mWebView
 ;%0A%0A 
@@ -1480,61 +1480,8 @@
 S);%0A
-        mCookieHandler = new CookieHandlerAdapter();%0A
     
@@ -1806,19 +1806,20 @@
 ontrols(
-tru
+fals
 e);%0A    
@@ -1942,24 +1942,102 @@
 led(true);%0A%0A
+        mWebView.addJavascriptInterface(new IdobataInterface(), %22$Idobata%22);%0A%0A
         mWeb
@@ -2932,24 +2932,198 @@
 ce.class));%0A
+                mWebView.loadUrl(%22javascript:document.getElementsByClassName('image-upload-field')%5B0%5D.addEventListener('click', function()%7B$Idobata.uploadFile()%7D, false);%22);%0A
             
@@ -4392,11 +4392,852 @@
 );%0A    %7D
+%0A%0A    @Override%0A    public void onActivityResult(int requestCode, int resultCode, Intent resultData) %7B%0A        if (requestCode == READ_REQUEST_CODE && resultCode == RESULT_OK) %7B%0A            Uri uri = null;%0A            if (resultData != null) %7B%0A                uri = resultData.getData();%0A                Toast.makeText(this, %22NOT IMPLEMENTED; %22 + uri, Toast.LENGTH_SHORT)%0A                     .show();%0A            %7D%0A        %7D%0A    %7D%0A%0A    private void performFileSearch() %7B%0A        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);%0A        intent.addCategory(Intent.CATEGORY_OPENABLE);%0A        intent.setType(%22image/*%22);%0A        startActivityForResult(intent, READ_REQUEST_CODE);%0A    %7D%0A%0A    private class IdobataInterface %7B%0A        @JavascriptInterface%0A        public void uploadFile() %7B%0A            performFileSearch();%0A        %7D%0A    %7D
 %0A%7D%0A

Handle upload(still developing).