package com.usai.apex.pdf;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.listener.OnPageErrorListener;
import com.github.barteksc.pdfviewer.util.FitPolicy;
import com.shockwave.pdfium.PdfDocument;
import com.usai.apex.ApexTrackingApplication;
import com.usai.apex.R;
import com.usai.util.RAUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

public class PDFPreviewActivity extends AppCompatActivity implements OnPageChangeListener, OnLoadCompleteListener,
        OnPageErrorListener {

    boolean iscachefile;
    private static final String TAG = PDFPreviewActivity.class.getSimpleName();
//    String pdfFileName;
    PDFView pdfView;
//    @NonConfigurationInstance
    Integer pageNumber = 0;
//    public static final String SAMPLE_FILE = "sample.pdf";



    protected void openFile() {

        String path=getIntent().getStringExtra("file");
        File file = new File(path);
        if (file == null || !file.exists()) {
            return;
        }

        Uri uri = null;
        String type = RAUtil.getMimeType(file.getPath());

        // type "application/pdf"
        Intent intent = new Intent(Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            // "com.usai.apex.fileprovider"即是在Manifest文件中配置的authorities
            uri = FileProvider.getUriForFile(this, "com.usai.apex.fileprovider", file);
            // 给目标应用一个临时授权
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }

        intent.setDataAndType(uri, type);

        if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            // someone knows how to handle this mime type with this scheme, don't download.
            try {
                startActivity(intent);
                return;
            } catch (Exception ex) {
                Log.d("Open File", "activity not found for " + type + " over " + uri, ex);
            }

        } else {
            Log.d("Open File", "openFileAtPath: " + "No App " + uri);


            AlertDialog.Builder builder = new AlertDialog.Builder(
                    PDFPreviewActivity.this);
            builder.setMessage("Can not open PDF file, no external App found." );

            builder.setTitle("Open PDF");

            builder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener()
            {

                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.dismiss();


                }
            });

            builder.create().show();

//            try {
//                shareFile(uri,type);
//            } catch (Exception e) {
//                Log.e("Show Dialog Error", "openFileAtPath: ", e);
//            }
        }

    }

    protected void shareFile(/*Uri uri, String type*/) {

        String path=getIntent().getStringExtra("file");
        File file = new File(path);
        if (file == null || !file.exists()) {
            return;
        }
        Uri uri = null;
        String type = RAUtil.getMimeType(file.getPath());


        String email_to = null,email_subject = null,email_content = null;
        String json_str = null;
        if (iscachefile) {

            json_str = getIntent().getStringExtra("email");
        } else {

            String filename = file.getName();
            String dir = file.getParent();
            json_str = RAUtil.readJson(dir + File.separator + filename + ".email");
        }
        if (json_str != null) {
            try {
                JSONObject email_json = new JSONObject(json_str);
                email_to = email_json.getString("email");
                email_subject = email_json.getString("subject");
                email_content = email_json.getString("content");
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

            // "com.usai.apex.fileprovider"即是在Manifest文件中配置的authorities
            uri = FileProvider.getUriForFile(this, "com.usai.apex.fileprovider", file);
            // 给目标应用一个临时授权
        } else {
            uri = Uri.fromFile(file);
        }

        Intent share = new Intent();
        share.setAction(Intent.ACTION_SEND);
        share.putExtra(Intent.EXTRA_STREAM, uri);
        share.setType(type);


        if (email_content != null) {
            share.putExtra(Intent.EXTRA_TEXT, email_content);   //附带的说明信息
        }
        if (email_subject != null) {
            share.putExtra(Intent.EXTRA_SUBJECT, email_subject);
        }
        if (email_to != null) {
            share.putExtra(Intent.EXTRA_EMAIL, email_to.split(","));
        }

//        share.putExtra(Intent.EXTRA_CC, new String[]{"ray.zhang@united-cn.net"});
//        startActivity(Intent.createChooser(share,getString(R.string.str_sendto)));
        startActivity(Intent.createChooser(share, "Share"));




//        Intent share = new Intent(Intent.ACTION_SEND);
//        String filename = (String) v.getTag();
//        share.putExtra(Intent.EXTRA_STREAM,
//                Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/Apex Mobile/"+filename)));
//        String[] token = filename.split("\\.");
//        String ext = token[token.length-1];
//        share.setType("application/"+ext);//此处可发送多种文件

    }

    private void setCustomActionBar() {
        ActionBar.LayoutParams lp =new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
        View mActionBarView = LayoutInflater.from(this).inflate(R.layout.actionbar_customtitle, null);

        String path=getIntent().getStringExtra("file");
        String title=new File(path).getName();
        TextView mtitleview= mActionBarView.findViewById(R.id.title);
//        String title = mParams.getString("title");
        mtitleview.setText(title);
        setTitle(title);
//
//        mActionBarView.setBackgroundColor(Color.YELLOW);
//        titleview.setBackgroundColor(Color.BLUE);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setCustomView(mActionBarView, lp);
//        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
//        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayHomeAsUpEnabled(true);


//        actionBar.setIcon(getNumberDrawable());
//        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayShowTitleEnabled(true);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            case android.R.id.home:
                finish();
                break;
            case R.id.action_save:
                SavePDF();
                break;
            case R.id.action_open:
                openFile();
                break;
            case R.id.action_send:
                shareFile();
                break;

            default: break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void SavePDF()
    {


        String todir=ApexTrackingApplication.getInstance().getDocumentDir();

//        String sourcefile=getIntent().getStringExtra("file");
        File source =new File(getIntent().getStringExtra("file"));
        String filename = source.getName();
//        boolean successful= source.renameTo(new File(todir+filename));

        boolean successful=RAUtil.copyFile(getIntent().getStringExtra("file"),todir+"/"+filename);
        String json_str = getIntent().getStringExtra("email");
        if (json_str != null) {
            RAUtil.writeJson(json_str,todir + File.separator + filename + ".email");
        }

//        Files.copy(source, Path target, CopyOption... options)

        String title= "Save document";
        String msg = "Can not save document";

        if(successful)
        {
            msg= "Document Saved";

        }

        AlertDialog.Builder builder = new AlertDialog.Builder(
                PDFPreviewActivity.this);
        builder.setMessage(msg);

        builder.setTitle(title);

        builder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener()
        {

            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();


            }
        });

        builder.create().show();

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.

        if(iscachefile)
            getMenuInflater().inflate(R.menu.pdf_cached_preview, menu);
        else
            getMenuInflater().inflate(R.menu.pdf_saved_preview, menu);
        return true;
    }
    @Override
    protected void onDestroy()
    {

        if(iscachefile) {
            String file = getIntent().getStringExtra("file");
            new File(file).delete();
        }
        super.onDestroy();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf_preview);

        setCustomActionBar();
        pdfView = findViewById(R.id.pdfView);
        pdfView.setBackgroundColor(Color.LTGRAY);
        pdfView.setPadding(10,10,10,10);

        String file=getIntent().getStringExtra("file");
        iscachefile = getIntent().getBooleanExtra("iscache",false);
//        pdfFileName = assetFileName;
        pdfView.fromFile(new File(file))
//        pdfView.fromAsset(SAMPLE_FILE)
                .defaultPage(pageNumber)
                .onPageChange(this)
                .enableAnnotationRendering(true)
                .onLoad(this)
//                .scrollHandle(new DefaultScrollHandle(this))

                .spacing(10) // in dp
                .onPageError(this)
                .pageFitPolicy(FitPolicy.BOTH)
                .load();

        /*
        pdfView.fromAsset(SAMPLE_FILE)
//                .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
                .enableSwipe(true) // allows to block changing pages using swipe
                .swipeHorizontal(false)
                .enableDoubletap(true)
                .defaultPage(0)
                // allows to draw something on the current page, usually visible in the middle of the screen
//                .onDraw(this)
                // allows to draw something on all pages, separately for every page. Called only for visible pages
//                .onDrawAll(onDrawListener)
                .onLoad(this) // called after document is loaded and starts to be rendered
                .onPageChange(this)
//                .onPageScroll(onPageScrollListener)
//                .onError(onErrorListener)
                .onPageError(this)
//                .onRender(onRenderListener) // called after document is rendered for the first time
                // called on single tap, return true if handled, false to toggle scroll handle visibility
//                .onTap(onTapListener)
                .enableAnnotationRendering(false) // render annotations (such as comments, colors or forms)
                .password(null)
                .scrollHandle(null)
                .enableAntialiasing(true) // improve rendering a little bit on low-res screens
                // spacing between pages in dp. To define spacing color, set view background
                .spacing(0)
//                .linkHandler(DefaultLinkHandler)
                .pageFitPolicy(FitPolicy.WIDTH)
                .load();*/
    }

    @Override
    public void loadComplete(int nbPages) {
        PdfDocument.Meta meta = pdfView.getDocumentMeta();
        Log.e(TAG, "title = " + meta.getTitle());
        Log.e(TAG, "author = " + meta.getAuthor());
        Log.e(TAG, "subject = " + meta.getSubject());
        Log.e(TAG, "keywords = " + meta.getKeywords());
        Log.e(TAG, "creator = " + meta.getCreator());
        Log.e(TAG, "producer = " + meta.getProducer());
        Log.e(TAG, "creationDate = " + meta.getCreationDate());
        Log.e(TAG, "modDate = " + meta.getModDate());

        printBookmarksTree(pdfView.getTableOfContents(), "-");
    }

    @Override
    public void onPageChanged(int page, int pageCount) {

    }

    @Override
    public void onPageError(int page, Throwable t) {

    }

    public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
        for (PdfDocument.Bookmark b : tree) {

            Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));

            if (b.hasChildren()) {
                printBookmarksTree(b.getChildren(), sep + "-");
            }
        }
    }
}
