package com.reactlibrary;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.reactlibrary.R;
import com.reactlibrary.JSBundleManager.JSBundleManagerUpdateType;
import com.reactlibrary.JSBundleManager.JSBundleManagerFrequency;
import com.reactlibrary.model.VersionDetails;
import com.reactlibrary.view.VersionAdapter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static com.reactlibrary.JSBundleManager.RNAU_SHARED_PREFERENCES;
import static com.reactlibrary.JSBundleManager.RNAU_STORED_VERSION;


/**
 * @author anbu
 */
public abstract class JSBundleManagerActivity extends AppCompatActivity
        implements JSBundleManager.Interface {

    protected static JSBundleManager updater;
    protected static boolean  _mAlreadyUpdated = false;
    protected static String metaDataURL;
    protected static String ostype;
    protected static String filenamename;

    public static String getProductName() {
        return productName;
    }

    protected static String  productName;

    public static String getOstype() {
        return ostype;
    }

    public static String getUpdateFileName() {
        return filenamename;
    }

    public static String getMetaDataURL() {
        return metaDataURL;
    }


    @Override
    public void onDestroy(){
        super.onDestroy();

//        updater = null;
    }

    public static JSBundleManager getBundleManager(Context context){
        if(updater == null){
            updater = JSBundleManager.getInstance(context);
            updater.setUpdateMetadataUrl(getUpdateDataUrl())
                    .setMetadataAssetName("metadata.android.json")
                    .setUpdateFrequency(JSBundleManagerFrequency.EACH_TIME)
                    .setUpdateTypesToDownload(JSBundleManagerUpdateType.PATCH)
                    .setHostnameForRelativeDownloadURLs(getMetaDataURL());
        }

        return updater;
    }


    public static String getUpdateDataUrl(){
        return getMetaDataURL()+"/"+getOstype()+"/"+getProductName()+"/"+getUpdateFileName();
    }

    protected String getHostnameForRelativeDownloadURLs() {
        return null;
    }

    protected JSBundleManagerUpdateType getAllowedUpdateType() {
        return JSBundleManagerUpdateType.PATCH;
    }

    protected JSBundleManagerFrequency getUpdateFrequency() {
        return JSBundleManagerFrequency.EACH_TIME;
    }

    @Override
    public void updateFinished() {
        this.recreate();
        SharedPreferences myPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        SharedPreferences prefs = getBaseContext().getSharedPreferences(RNAU_SHARED_PREFERENCES, Context.MODE_PRIVATE);

        String ver = prefs.getString(RNAU_STORED_VERSION,"1.0");
        SharedPreferences.Editor appversioneditor = myPrefs.edit();

        appversioneditor.putString("key_appversion",ver);
        appversioneditor.commit();
        _mAlreadyUpdated = true;
    }

    protected abstract void refreshFragment();

    @Override
    public void onNewVersionAvailable(final String version){
        try {

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this, R.style.Theme_AppCompat_Light_Dialog);
            alertDialogBuilder.setTitle(R.string.auto_updater_downloaded_title);
            alertDialogBuilder
                    .setMessage("A latest version ("+version+") is available.Do you want to Download it?")
                    .setCancelable(false)
                    .setIcon(R.drawable.ic_action_update)
                    .setPositiveButton(
                            R.string.auto_updater_downloaded_now,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    updater.downloadNewversion(version);
                                }
                            }
                    )
                    .setNegativeButton(
                            R.string.auto_updater_downloaded_later,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            }
                    );

            AlertDialog alertDialog = alertDialogBuilder.create();
            alertDialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void bundlesFetched(final ArrayList<VersionDetails> versionDetailList) {

        Dialog dialog = new Dialog(this);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        ListView modeList = new ListView(this);

//        VersionAdapter<VersionDetails> modeAdapter = new VersionAdapter<VersionDetails>(this,versionList);



        LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View headerView = inflater.inflate(R.layout.listview_header, null, false);
        modeList.addHeaderView(headerView);

        View footerView = inflater.inflate(R.layout.listview_footer, null, false);
        modeList.addFooterView(footerView);

        List<String> versionList = getVersionsFromArrayList(versionDetailList);
        // Create a List from String Array elements
        final List<String> fruits_list = new ArrayList<String>(versionList);

        // Create an ArrayAdapter from List
        final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
                (this, android.R.layout.simple_list_item_1, fruits_list);


        modeList.setAdapter(arrayAdapter);
        builder.setView(modeList);
        dialog = builder.create();
        dialog.show();

        final Dialog finalDialog = dialog;
        modeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                                    long id) {
                String version = (String) parent.getItemAtPosition(position);
                updater.downloadNewversion(version);
                finalDialog.hide();

            }
        });

        Button cancelButton = (Button) footerView.findViewById(R.id.cancel);
        if(cancelButton != null){
            cancelButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finalDialog.hide();
                }
            });
        }
    }

    private List<String> getVersionsFromArrayList(ArrayList<VersionDetails> versionList) {
        List<String> versions = new ArrayList<String>();
        for (VersionDetails version: versionList) {
            versions.add(version.getTitle());
        }
        return versions;
    }
}