/*
 * Copyright (C) 2012,2013 Renard Wellnitz.
 * 
 * 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.renard.documentview;

import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.renard.documentview.DocumentActivity.DocumentContainerFragment;
import com.renard.ocr.R;
import com.renard.util.PreferencesUtils;
import com.viewpagerindicator.CirclePageIndicator;

public class DocumentPagerFragment extends Fragment implements DocumentContainerFragment {

    private ViewPager mPager;
    private CirclePageIndicator mTitleIndicator;
    private boolean mIsTitleIndicatorVisible = false;
    private boolean mIsNewCursor;
    private Cursor mCursor;
    DocumentAdapter mAdapter;
    private int mLastPosition = -1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_document_pager, container, false);
        mPager = (ViewPager) v.findViewById(R.id.document_pager);
        mTitleIndicator = (CirclePageIndicator) v.findViewById(R.id.titles);
        mLastPosition = -1;
        initPager();
        return v;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        boolean isKeyboardHidden = Configuration.KEYBOARDHIDDEN_YES == newConfig.hardKeyboardHidden;
        boolean isKeyboardShown = Configuration.KEYBOARDHIDDEN_NO == newConfig.hardKeyboardHidden;
        if (isKeyboardShown) {
            showTitleIndicator(false);
        } else if (isKeyboardHidden) {
            showTitleIndicator(true);
        }
    }


    private void showTitleIndicator(final boolean show) {
        if (mIsTitleIndicatorVisible) {
            if (show) {
                mTitleIndicator.setVisibility(View.VISIBLE);
            } else {
                mTitleIndicator.setVisibility(View.GONE);
            }
        }
    }

    public void applyTextPreferences() {
        final int count = mPager.getChildCount();
        for (int i = 0; i < count; i++) {
            View v = mPager.getChildAt(i);
            EditText e = (EditText) v.findViewById(R.id.editText_document);
            PreferencesUtils.applyTextPreferences(e, getActivity());
        }
    }

    public void setDisplayedPage(final int pageno) {
        mPager.setCurrentItem(pageno, true);
    }
    public void setDisplayedPageByDocumentId(final int documentId) {
        final int count = mAdapter.getCount();
        for(int i = 0; i < count; i++){
            final int id = mAdapter.getId(i);
            if(documentId==id) {
                mPager.setCurrentItem(i, false);
                return;
            }
        }
    }

    private void initPager() {

        if (mIsNewCursor && mPager != null) {


            if (mAdapter != null) {
                mAdapter.setCursor(mCursor);
            } else {
                mAdapter = new DocumentAdapter(getFragmentManager(), mCursor);
                mPager.setAdapter(mAdapter);
            }

            if (mAdapter.getCount() > 1) {
                mTitleIndicator.setViewPager(mPager);
                mIsTitleIndicatorVisible = true;
            } else {
                mTitleIndicator.setVisibility(View.GONE);
            }

            mTitleIndicator.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int position) {
                    if (mLastPosition != -1) {
                        final DocumentTextFragment fragment = mAdapter.getFragment(mLastPosition);
                        if(fragment!=null) {
                            fragment.saveIfTextHasChanged();
                        }
                    }
                    mLastPosition = position;
                    final String title = mAdapter.getLongTitle(position);
                    ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(title);
                    ((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayShowTitleEnabled(true);
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                }
            });
            mIsNewCursor = false;
        }
    }

    @Override
    public String getLangOfCurrentlyShownDocument() {
        DocumentAdapter adapter = (DocumentAdapter) mPager.getAdapter();
        int currentItem = mPager.getCurrentItem();
        return adapter.getLanguage(currentItem);
    }

    @Override
    public void setCursor(Cursor cursor) {
        mIsNewCursor = true;
        mCursor = cursor;
        initPager();
    }

    @Override
    public String getTextOfAllDocuments() {
		int position =0 ;
		if (mLastPosition!=-1){
			position = mLastPosition;
		}

		final DocumentTextFragment fragment = mAdapter.getFragment(position);

        DocumentAdapter adapter = (DocumentAdapter) mPager.getAdapter();
        final int count = adapter.getCount();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < count; i++) {
            String text;
            if(i==position){
                text = Html.toHtml(fragment.getDocumentText());
            } else {
                text = adapter.getText(i);
            }
            if (text != null) {
                if (sb.length() > 0) {
                    sb.append("\n");
                }
                sb.append(text);
            }
        }
        return sb.toString();
    }

    @Override
    public void setShowText(boolean text) {
        mAdapter.setShowText(text);
    }

    @Override
    public boolean getShowText() {
        return mAdapter.getShowText();
    }

}

@@ -956,16 +956,76 @@
 t.Html;%0A
+import android.text.Spanned;%0Aimport android.text.TextUtils;%0A
 import a
@@ -6183,16 +6183,23 @@
 ing text
+ = null
 ;%0A      
@@ -6241,55 +6241,191 @@
     
-text = Html.toHtml(fragment.getDocumentText());
+final Spanned documentText = fragment.getDocumentText();%0A                if(!TextUtils.isEmpty(documentText)) %7B%0A                    text = Html.toHtml(documentText);%0A                %7D
 %0A   

check ocr text for null