package com.sharefaith.thesharefaithapp.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.dynamiclinks.FirebaseDynamicLinks;
import com.google.firebase.dynamiclinks.PendingDynamicLinkData;
import com.sharefaith.thesharefaithapp.R;
import com.sharefaith.thesharefaithapp.SFMainActivity;
import com.sharefaith.thesharefaithapp.base.SFAppData;
import com.sharefaith.thesharefaithapp.base.SFApplication;
import com.sharefaith.thesharefaithapp.base.SFConfig;

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

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Locale;

/**
 * Created by sfwebsitedev on 1/4/18.
 */

public class SFChurchChooserActivity extends Activity
{
    private SFApplication mApplication;
    private SFConfig mConfig;
    private SFAppData mAppData;

    //private View mView;
    private EditText mSearchChurch;
    private ListView mChurchPicker;
    private Button mSaveButton;
    private ImageView mBackButton;

    private String TAG = "SFChurchChooseActivity";

    private static final String CHURCHLIST_URL = "https://appserve.sharefaith.com/singleApp.php?action=getChurchList";
    private ArrayList<ChurchModel> mArrayList = new ArrayList<>();
    private ChurchListArrayAdapter mChurchListArrayAdapter;
    private ChurchModel mSelectedChurch;

    @Override
    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );

        this.requestWindowFeature( Window.FEATURE_NO_TITLE );
        setContentView( R.layout.sf_church_chooser );

        //if not tablet keep screen from rotating
        if( !SFConfig.isTablet() )
        {
            setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_PORTRAIT );
        }

        mApplication = SFApplication.getInstance();
        mAppData = new SFAppData();

        FirebaseDynamicLinks.getInstance()
                .getDynamicLink(getIntent())
                .addOnSuccessListener(this, new OnSuccessListener<PendingDynamicLinkData>() {
                    @Override
                    public void onSuccess(PendingDynamicLinkData pendingDynamicLinkData) {
                        // Get deep link from result (may be null if no link is found)
                        Uri deepLink = null;
                        if (pendingDynamicLinkData != null) {


                            deepLink = pendingDynamicLinkData.getLink();
                            final int uaidLength = 16;
                            String url = deepLink.toString();
                            int uaidIndex = url.indexOf( "uaid=" ) + 5;
                            final String uaid = url.substring( uaidIndex, uaidIndex + uaidLength );
                            Log.e( "deeplink uaid: ", uaid );
                            if(!mApplication.getSfCurrentChurch().equals( uaid ))
                            {
                                mApplication.setCurrentChurchFromUAID( uaid );

                                AlertDialog alertDialog = new AlertDialog.Builder(SFChurchChooserActivity.this).create();
                                alertDialog.setTitle("App Icon");
                                alertDialog.setMessage("Which icon would you like to use for the home screen?");
                                alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "My Ministry", new DialogInterface.OnClickListener() {

                                    public void onClick(DialogInterface dialog, int id) {
                                        mApplication.setAppIcon(uaid);

                                        restartApp();
                                    } });

                                alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Default", new DialogInterface.OnClickListener() {

                                    public void onClick(DialogInterface dialog, int id) {
                                        mApplication.setAppIcon("default");

                                        restartApp();
                                    }});

                                alertDialog.show();

//								// Start Full Sync
//								SFAppData data = new SFAppData();
//								SFConfig config = new SFConfig();
//								data.deleteAllDatabaseData();
//								mApplication.deleteFilesFromDir( new File( config.mCustomAssetPath ) );
//								mApplication.nullifyNavMenuAdapter();
//								SFAppData.saveSyncTime( 0 );
//								mApplication.isSyncing = false;
//
//								Intent intent = new Intent( mApplication, SFMainActivity.class );
//								startActivity( intent );
//								overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
                            }
                        }
                        else
                        {
                            Log.e("ERROR", "No Dynamic Link found");
                        }


                        // Handle the deep link. For example, open the linked
                        // content, or apply promotional credit to the user's
                        // account.
                        // ...

                        // ...
                    }
                })
                .addOnFailureListener(this, new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.w(TAG, "getDynamicLink:onFailure", e);
                    }
                });

        //Create church list
        try
        {
            URL url = new URL( CHURCHLIST_URL );
            ChurchPickerDownloadTask task = new ChurchPickerDownloadTask( this.mApplication, this );
            task.execute( url );
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        }
    }

    protected void restartApp()
    {
        if(!mApplication.getSfCurrentChurch().equals( "0" ))
        {
            //   mApplication.isDoingFullSync = true;
            SFAppData data = new SFAppData();
            SFConfig config = new SFConfig();
            data.deleteAllDatabaseData();
            mApplication.deleteFilesFromDir( new File( config.mCustomAssetPath ) );
            mApplication.nullifyNavMenuAdapter();
            SFAppData.saveSyncTime( 0 );
            mApplication.isSyncing = false;
        }

        Intent intent = new Intent( mApplication , SFMainActivity.class );
        intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY );
        startActivity( intent );finish();
        overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
    }

    @Override
    protected void onResume()
    {
        super.onResume();

        //Google Analytics tracking
        mApplication.logScreen("church_chooser");

        mApplication.setCurrentActivity( this );
        mApplication.currentViewTag = "churchChooser";
        mApplication.currentSectionPosition = -1;

        mConfig = new SFConfig();
        //Get a list of the current live apps
        try
        {
            URL url = new URL( CHURCHLIST_URL );
            ChurchPickerDownloadTask task = new ChurchPickerDownloadTask( this.mApplication, this );
            task.execute( url );
        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        }

        this.mSearchChurch = (EditText) findViewById( R.id.text_search_church );
        this.mSearchChurch.setOnEditorActionListener(new DoneOnEditorActionListener());
        this.mChurchPicker = (ListView) findViewById( R.id.listView_choose_church );
        this.mSaveButton = (Button) findViewById( R.id.button_save );
        this.mBackButton = (ImageView) findViewById( R.id.back_button );

        this.mArrayList = new ArrayList<>();
        this.mChurchListArrayAdapter = new ChurchListArrayAdapter( this.mApplication,this.mArrayList ,this.mSelectedChurch);
        this.mChurchPicker.setAdapter( this.mChurchListArrayAdapter );

        // Filter the list of church apps based on the text in the input
        this.mSearchChurch.addTextChangedListener( new TextWatcher()
        {
            @Override
            public void beforeTextChanged( CharSequence s, int start, int count, int after )
            {

            }

            @Override
            public void onTextChanged( CharSequence s, int start, int before, int count )
            {

            }

            @Override
            public void afterTextChanged( Editable s )
            {
                String text = mSearchChurch.getText().toString().toLowerCase();
                mChurchListArrayAdapter.filter(text);
            }
        } );

        //Get the info of the church app selected
        this.mChurchPicker.setOnItemClickListener( new AdapterView.OnItemClickListener()
        {
            @Override
            public void onItemClick( AdapterView<?> parent, View view, int position, long id )
            {
                mSelectedChurch = mChurchListArrayAdapter.mFilteredList.get( position );
                mSearchChurch.setText( mSelectedChurch.mChurchName.toString() );
                mChurchListArrayAdapter = new ChurchListArrayAdapter( mApplication, mArrayList, mSelectedChurch );
                mChurchPicker.setAdapter( mChurchListArrayAdapter );
                mChurchListArrayAdapter.filter(mSearchChurch.getText().toString());
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(mChurchPicker.getWindowToken(), 0);
            }
        } );

        //Make sure the user chose an app. Set the church app wide and restart the app and pull in the data for newly selected church
        this.mSaveButton.setOnClickListener( new View.OnClickListener()
        {
            @Override
            public void onClick( final View v )
            {
                if(mSelectedChurch != null && mSelectedChurch.mChurchName.toString().equals( mSearchChurch.getText().toString() ))
                {
                    mApplication.setCurrentChurch( mSelectedChurch.mUaid.toString() );

                    AlertDialog alertDialog = new AlertDialog.Builder(v.getContext()).create();
                    alertDialog.setTitle("App Icon");
                    alertDialog.setMessage("Which icon would you like to use for the home screen?");
                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "My Ministry", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int id) {
                            mApplication.setAppIcon(mSelectedChurch.mUaid.toString());

                            if(!mApplication.getSfCurrentChurch().equals( "0" ))
                            {
                                //   mApplication.isDoingFullSync = true;
                                SFAppData data = new SFAppData();
                                SFConfig config = new SFConfig();
                                data.deleteAllDatabaseData();
                                mApplication.deleteFilesFromDir( new File( config.mCustomAssetPath ) );
                                mApplication.nullifyNavMenuAdapter();
                                SFAppData.saveSyncTime( 0 );
                                mApplication.isSyncing = false;
                            }

                            Intent intent = new Intent( mApplication , SFMainActivity.class );
                            intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
                            startActivity( intent );
                            overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
                        } });

                    alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Default", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int id) {
                            mApplication.setAppIcon("default");

                            if(!mApplication.getSfCurrentChurch().equals( "0" ))
                            {
                                //   mApplication.isDoingFullSync = true;
                                SFAppData data = new SFAppData();
                                SFConfig config = new SFConfig();
                                data.deleteAllDatabaseData();
                                mApplication.deleteFilesFromDir( new File( config.mCustomAssetPath ) );
                                mApplication.nullifyNavMenuAdapter();
                                SFAppData.saveSyncTime( 0 );
                                mApplication.isSyncing = false;
                            }

                            Intent intent = new Intent( mApplication , SFMainActivity.class );
                            intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
                            startActivity( intent );
                            overridePendingTransition( R.anim.sf_activity_slidein_right, R.anim.sf_activity_slideout_left );
                        }});

                    alertDialog.show();
                }
                else
                {
                    SFApplication.makeToast( "Please select a church" );
                }
            }
        } );

        // If no church has been selected before, they have to choose a church before they can do anything
        if(this.mApplication.getSfCurrentChurch().equals( "0" ))
        {
            this.mBackButton.setVisibility( View.GONE );
        }
        else
        {
            this.mBackButton.setOnClickListener( new View.OnClickListener()
            {
                @Override
                public void onClick( View v )
                {
                    finish();
                    overridePendingTransition( R.anim.sf_activity_slidein_left, R.anim.sf_activity_slideout_right );
                }
            } );
        }
    }

    private void setupChurchList()
    {
        this.mArrayList = new ArrayList<>();
        JSONObject churchList = mApplication.churchList;
        try
        {
            Iterator<String> temp = churchList.keys();
            while (temp.hasNext())
            {
                String name = temp.next();
                JSONObject jsonObject = (JSONObject) churchList.get( name );
                String uaid = (String) jsonObject.get( "id" );
                ChurchModel churchModel = new ChurchModel( name,uaid );
                this.mArrayList.add( churchModel);
            }
            this.mChurchListArrayAdapter = new ChurchListArrayAdapter( this.mApplication,this.mArrayList, this.mSelectedChurch );
            this.mChurchPicker.setAdapter( this.mChurchListArrayAdapter );
            this.mChurchListArrayAdapter.filter(this.mSearchChurch.getText().toString());
        }
        catch (JSONException e)
        {

        }
    }

    //hide keyboard when Done is clicked
    class DoneOnEditorActionListener implements TextView.OnEditorActionListener
    {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                InputMethodManager imm = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                return true;
            }
            return false;
        }
    }

    @Override
    public void onBackPressed()
    {
        this.finish();
        overridePendingTransition( R.anim.sf_activity_slidein_left, R.anim.sf_activity_slideout_right );
    }

    /** A simple model for the church data
     *
     */
    private class ChurchModel
    {
        public String mChurchName = "";
        public String mUaid = "";

        /**
         * MoreModel constructor
         * @param churchName
         * @param uaid
         */
        public ChurchModel( String churchName, String uaid )
        {
            this.mChurchName = churchName;
            this.mUaid = uaid;
        }
    }

    /**
     * An ArrayAdapter to hold the churchList
     */
    private class ChurchListArrayAdapter extends BaseAdapter
    {
        Context mContext;
        LayoutInflater mInflater;
        private ArrayList<ChurchModel> mList = null;
        private ArrayList<ChurchModel> mFilteredList = null;
        private ChurchModel mCurrentChurch = null;

        public ChurchListArrayAdapter( Context context, ArrayList<ChurchModel> list, ChurchModel currentChurch)
        {
            this.mContext = context;
            this.mList = list;
            this.mInflater = LayoutInflater.from( this.mContext );
            this.mFilteredList = new ArrayList<>();
            this.mFilteredList.addAll( this.mList );
            this.mCurrentChurch = currentChurch;
        }

        public class ViewHolder
        {
            public TextView churchName;
            public ImageView check;
//            public int position;
        }

        @Override
        public int getCount()
        {
            return this.mFilteredList.size();
        }

        @Override
        public Object getItem( int position )
        {
            return mFilteredList.get( position );
        }

        @Override
        public long getItemId( int position )
        {
            return position;
        }

        public View getView( int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;

            if (convertView == null)
            {
                holder = new ViewHolder();
                convertView = this.mInflater.inflate( R.layout.sf_church_list_item, null );
                holder.churchName = (TextView) convertView.findViewById( R.id.church_name );
                holder.check = (ImageView) convertView.findViewById( R.id.image_check );
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }

            ChurchModel currentObject = this.mFilteredList.get( position );

            //Log.d( "mtag", "currentObject churchName: " + currentObject.mChurchName.toString() + ", uaid: " + currentObject.mUaid );

            if( currentObject != null ) //Set the variable things, title and excerpt, even if not creating.
            {
                if( holder.churchName != null )
                {
                    holder.churchName.setText( currentObject.mChurchName );
                    
                    if( this.mCurrentChurch != null && currentObject.mChurchName.toString().equals( this.mCurrentChurch.mChurchName.toString() ) )
                    {
                        holder.check.setVisibility( View.VISIBLE );
                    }
                    else
                    {
                        holder.check.setVisibility( View.INVISIBLE );
                    }
                }
                convertView.setTag(holder);
            }

            return convertView;

        }

        public void filter(String charText) {
            charText = charText.toLowerCase( Locale.getDefault());
            this.mFilteredList.clear();
            if (charText.length() < 3) {
                mChurchPicker.setVisibility( View.GONE );
            }
            else
            {
                for (ChurchModel cm : mList)
                {
                    if (cm.mChurchName.toLowerCase( Locale.getDefault() ).contains(charText))
                    {
                        mFilteredList.add(cm);
                    }
                }
                mChurchPicker.setVisibility( View.VISIBLE );
            }
            notifyDataSetChanged();
        }
    }

    /**
     * Download task to run in the background
     */
    public class ChurchPickerDownloadTask extends AsyncTask<URL, Integer, JSONObject>
    {
        private final SFChurchChooserActivity mParent;
        public SFApplication mCaller;
        public String mResult;
        public boolean mHadError = false;

        /**
         * Constructor
         *
         * @param caller
         */
        public ChurchPickerDownloadTask( SFApplication caller, SFChurchChooserActivity parent )
        {
            this.mCaller = caller;
            this.mParent = parent;
            this.mResult = "";
        }

        /**
         * @param urls
         * @return
         */
        @Override
        protected JSONObject doInBackground( URL... urls )
        {
            JSONObject returnValue = null;
            try
            {
                BufferedReader in = new BufferedReader( new InputStreamReader( urls[0].openStream() ) );
                String line;

                while ((line = in.readLine()) != null)
                {
                    if (line.equalsIgnoreCase( "bye" ))
                    {
                        Log.e( "SOCKET ERROR", "Socket said goodbye" );
                    }
                    //get lines
                    this.mResult += line;
                }
                returnValue = new JSONObject( this.mResult );
                //Log.d( "jsonObject","jsonObject = " + returnValue );
                in.close();
            } catch (Exception e)
            {
                this.mHadError = true;
                String message = SFApplication.getInstance().getString( R.string.sync_error ) + e.getLocalizedMessage();
                SFApplication.makeToast( message );
            }
            return returnValue;

//            int count = urls.length;
//            long totalSize = 0;
//            for( int i = 0; i < count; i++ )
//            {
//                //totalSize += Downloader.downloadFile( urls[i] );
//                publishProgress( (int) ((i / (float) count) * 100) );
//                // Escape early if cancel() is called
//                if( isCancelled() ) { break; }
//            }
//            return totalSize;
        }

        @Override
        protected void onProgressUpdate( Integer... progress )
        {
            //setProgressPercent(progress[0]);
        }

        /**
         * @param result
         */
        // run the next piece of the chain
        @Override
        protected void onPostExecute( final JSONObject result )
        {

            // onPostExecute runs on the main thread, which will pause the UI if we allow it to do so
            runOnUiThread( new Runnable()
            {
                public void run()
                {
                    mCaller.churchList = result;
                    mParent.setupChurchList();
                  //  Log.d( "churchList", String.valueOf( result ) );
                }
            });
           // t.start();
        }

    }
}
