package edu.uoc.prezmm.a1list2cook;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import edu.uoc.prezmm.a1list2cook.objects_class.Users;

public abstract class BaseActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private ActionBarDrawerToggle toggle;

    final int ReadExternalRequestCode = 200;

    NavigationView navigationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);

        //Especificació del Toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //Declaració del menú desplegable
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        //Vinculació amb el contingut del menú
        navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    //Comportament del botó per tornar enrere quan el menú esta desplegat
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        //Comprova si s'esta mostrant el menú, si es aixi l'oculta
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    //Prepara el menú principal
    public boolean onPrepareOptionsMenu(Menu menu) {
        //Espscifica el nom de l'usuari al menu
        SharedPreferences prefs = getSharedPreferences("UserInfo", Context.MODE_PRIVATE);
        Users userInfo = new Users(prefs);
        String userName = userInfo.getUserName();
        TextView userNameNav = (TextView)findViewById(R.id.userNameNav);
        userNameNav.setText(userName);

        //Vincula el logo del menú amb la pàgina principal de la APP
        ImageView logoNav = (ImageView)findViewById(R.id.logoNav);
        logoNav.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                changeActivity(HomeActivity.class);
            }
        });

        return super.onPrepareOptionsMenu(menu);
    }


    @Override
    //Gestió de les funcionalitats dels elements del menú principal
    public boolean onNavigationItemSelected(MenuItem item) {
        //Emmagatzema el ID de l'element del menú al que s'ha fet click
        int id = item.getItemId();

        //Comportaments dels elements del menú
        if (id == R.id.nav_recipes_list) {
            changeActivity(RecipesListActivity.class);
        } else if (id == R.id.nav_recipes_search) {
            changeActivity(RecipesSearchActivity.class);
        } else if (id == R.id.nav_recipes_add) {
            changeActivity(RecipeAddActivity.class);
        } else if (id == R.id.nav_lists_list) {
            changeActivity(ListsListActivity.class);
        } else if (id == R.id.nav_lists_add) {
            changeActivity(ListAddActivity.class);
        } else if (id == R.id.nav_tutorial) {
            changeActivity(TutorialActivity.class);
        } else if (id == R.id.nav_settings) {
            changeActivity(SettingsActivity.class);
        } else if (id == R.id.nav_logout) {
            changeActivity(LoginActivity.class);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //Especificar contingut del layout al frame base
    protected void setLayoutToBaseFrame(int activityLayout) {
        FrameLayout contentFrameLayout = (FrameLayout) findViewById(R.id.content_frame);
        getLayoutInflater().inflate(activityLayout, contentFrameLayout);
    }

    //Especificar el títol del ToolBar
    protected void setToolBarTitle(String title) {
        getSupportActionBar().setTitle("");
        getSupportActionBar().setTitle(title);
    }

    //Ocultar la icona de menu del ToolBar
    protected void hideToolBarMenu() {
        lockMenu();
        toggle.setDrawerIndicatorEnabled(false);
    }

    //Ocultar el ToolBar
    protected void hideToolBar() {
        lockMenu();
        getSupportActionBar().hide();
    }

    //Inhabilitar menu desplegable
    private void lockMenu() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    }

    //Canviar de Activity
    protected void changeActivity(Class Target) {
        startActivity(new Intent(this, Target));
    }

    //Canviar de Activity i passa un paràmetre
    protected void changeActivity(Class Target,String idExtra,String valueExtra) {
        Intent intent = new Intent(this, Target);
        intent.putExtra(idExtra, valueExtra);
        startActivity(intent);
    }
    //Canviar de Activity i passa dos paràmetre
    protected void changeActivity(Class Target,String idExtra,String valueExtra,String idExtra2,String valueExtra2) {
        Intent intent = new Intent(this, Target);
        intent.putExtra(idExtra, valueExtra);
        intent.putExtra(idExtra2, valueExtra2);
        startActivity(intent);
    }

    //Missatges per pantalla
    public void showMessage(String message) {
        Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER|Gravity.CENTER,0,0);
        toast.show();
    }

    //Comprovació de permissos necessaris
    public boolean checkPermission(final Context context) {
        int currentAPIVersion = Build.VERSION.SDK_INT;
        if (currentAPIVersion >= android.os.Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                    alertBuilder.setCancelable(true);
                    alertBuilder.setTitle("Permission necessary");
                    alertBuilder.setMessage("External storage permission is necessary");
                    alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, ReadExternalRequestCode);
                        }
                    });
                    AlertDialog alert = alertBuilder.create();
                    alert.show();
                } else {
                    ActivityCompat.requestPermissions((Activity) context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, ReadExternalRequestCode);
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }
}
