/*
 * Copyright (c) 2013 IRCCloud, Ltd.
 *
 * 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.irccloud.android.activity;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.irccloud.android.R;

import java.util.Timer;
import java.util.TimerTask;

public class ImageViewerActivity extends BaseActivity {
    WebView mImage;
    ProgressBar mProgress;
    Timer mHideTimer;

    public class JSInterface {
        @JavascriptInterface
        public void imageFailed() {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getIntent().getDataString().replace("irccloud-image", "http")));
            startActivity(intent);
            finish();
        }

        @JavascriptInterface
        public void imageClicked() {
            ImageViewerActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    getSupportActionBar().show();
                    hide_actionbar();
                }
            });
        }
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState == null)
            overridePendingTransition(R.anim.slide_in_right, R.anim.fade_out);
        setContentView(R.layout.activity_imageviewer);
        if(Integer.parseInt(Build.VERSION.SDK) >= 11 && Integer.parseInt(Build.VERSION.SDK) < 19)
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        getSupportActionBar().setTitle("Image Viewer");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mImage = (WebView)findViewById(R.id.image);
        mImage.setBackgroundColor(0);
        mImage.addJavascriptInterface(new JSInterface(), "Android");
        mImage.getSettings().setBuiltInZoomControls(true);
        if(Integer.parseInt(Build.VERSION.SDK) >= 19)
            mImage.getSettings().setDisplayZoomControls(false);
        mImage.getSettings().setJavaScriptEnabled(true);
        mImage.getSettings().setLoadWithOverviewMode(true);
        mImage.getSettings().setUseWideViewPort(true);
        mImage.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                mProgress.setVisibility(View.GONE);
                mImage.setVisibility(View.VISIBLE);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getIntent().getDataString().replace("irccloud-image", "http")));
                startActivity(intent);
                finish();
            }
        }
        );
        mProgress = (ProgressBar)findViewById(R.id.progress);

        if(getIntent() != null && getIntent().getDataString() != null) {
            mImage.loadDataWithBaseURL(null,"<!DOCTYPE html>\n" +
                    "<html>\n" +
                    "<body bgcolor='#000'>\n" +
                    "<img src='" + getIntent().getDataString().replace("irccloud-image", "http") + "' width='100%' style='top:0; bottom:0; margin: auto; position: absolute;'  onerror='Android.imageFailed()' onclick='Android.imageClicked()'/>\n" +
                    "</body>\n" +
                    "</html>", "text/html", "UTF-8",null);
        } else {
            finish();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        hide_actionbar();
    }

    private void hide_actionbar() {
        if(mHideTimer != null)
            mHideTimer.cancel();
        mHideTimer = new Timer();
        mHideTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                ImageViewerActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        getSupportActionBar().hide();
                    }
                });
                mHideTimer = null;
            }
        }, 5000);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.fade_in, R.anim.slide_out_right);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_imageviewer, menu);

        if(getIntent() != null && getIntent().getDataString() != null) {
            Intent intent = new Intent(Intent.ACTION_SEND, Uri.parse(getIntent().getDataString().replace("irccloud-image", "http")));
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_TEXT, getIntent().getDataString().replace("irccloud-image", "http"));

            MenuItem shareItem = menu.findItem(R.id.action_share);
            ShareActionProvider share = (ShareActionProvider)MenuItemCompat.getActionProvider(shareItem);
            share.setShareIntent(intent);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home) {
            finish();
            overridePendingTransition(R.anim.fade_in, R.anim.slide_out_right);
            return true;
        } else if(item.getItemId() == R.id.action_browser) {
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(getIntent().getDataString().replace("irccloud-image", "http")));
            startActivity(intent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

@@ -3954,32 +3954,289 @@
 ng() != null) %7B%0A
+            String url = getIntent().getDataString().replace(%22irccloud-image%22, %22http%22);%0A            if(url.toLowerCase().startsWith(%22http://www.dropbox.com/%22) %7C%7C url.toLowerCase().startsWith(%22https://www.dropbox.com/%22))%0A                url = url + %22?dl=1%22;%0A
             mIma
@@ -4405,69 +4405,11 @@
 %22 + 
-getIntent().getDataString().replace(%22irccloud-image%22, %22http%22)
+url
  + %22

Append ?dl=1 to www.dropbox.com image URLs so they open in the in-app viewer