package com.example.nuria.fesp_cyl;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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.Menu;
import android.view.MenuItem;

import com.example.nuria.fesp_cyl.Categories.AutonomicaFragment;
import com.example.nuria.fesp_cyl.Categories.EnsenanzaFragment;
import com.example.nuria.fesp_cyl.Categories.SanidadFragment;
import com.example.nuria.fesp_cyl.Categories.ServiciosFragment;
import com.example.nuria.fesp_cyl.Categories.SocioFragment;
import com.example.nuria.fesp_cyl.DataBase.DbHelper;
import com.example.nuria.fesp_cyl.DataBase.StatusContract;
import com.example.nuria.fesp_cyl.FragmentStatic.AfiliateFragment;
import com.example.nuria.fesp_cyl.FragmentStatic.AvisoFragment;
import com.example.nuria.fesp_cyl.FragmentStatic.ContactoFragment;
import com.example.nuria.fesp_cyl.FragmentStatic.InicioFragment;
import com.example.nuria.fesp_cyl.FragmentStatic.SomosFragment;
import com.example.nuria.fesp_cyl.Opciones.BuscarActivity;
import com.example.nuria.fesp_cyl.Opciones.SettingsActivity;
import com.example.nuria.fesp_cyl.Opciones.SiguenosActivity;

import java.util.ArrayList;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    ProgressDialog progressDialog = null;
    private int seg = 3000;
    private RefreshService service;


    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);


        progressDialog = new ProgressDialog(this);
        progressDialog.show();
        progressDialog.setContentView(R.layout.espera);
        //se podra cerrar simplemente pulsando back
        progressDialog.setCancelable(true);
        esperarYCerrar(seg);

        //add this line to display menu1 when the activity is loaded
        displaySelectedScreen(R.id.nav_home);

        startService(new Intent(this,RefreshService.class));
        service = new RefreshService();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_buscar:
                startActivity(new Intent(this, BuscarActivity.class));
                return true;
            case R.id.action_settings:
                startActivity(new Intent(this, SettingsActivity.class));
                return true;
            case R.id.action_seguir:
                startActivity(new Intent(this, SiguenosActivity.class));
                return true;
            default:
                return false;
        }

    }

    public void esperarYCerrar(int milisegundos) {
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            public void run() {
                // acciones que se ejecutan tras los milisegundos
                progressDialog.dismiss();
            }
        }, milisegundos);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {

        progressDialog = new ProgressDialog(this);
        progressDialog.show();
        progressDialog.setContentView(R.layout.espera);
        //se podra cerrar simplemente pulsando back
        progressDialog.setCancelable(true);
        //calling the method displayselectedscreen and passing the id of selected menu
        displaySelectedScreen(item.getItemId());
        return true;
    }

    private void displaySelectedScreen(int itemId){

        //creating fragment object
        Fragment fragment = null;
        NoticiasFragment fragmentList = null;

        //initializing the fragment object which is selected
        switch (itemId) {
            case R.id.nav_home:
                fragment = new InicioFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_servicios:
                fragment = new ServiciosFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_autonomica:
                fragment = new AutonomicaFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_formacion:
                service.nuevoUrl = putUrl("Formación");
                fragmentList = new NoticiasFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_sanidad:
                fragment = new SanidadFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_socio:
                fragment = new SocioFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_ensenanza:
                fragment = new EnsenanzaFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_publica:
                service.nuevoUrl = putUrl("E. Pública");
                fragmentList = new NoticiasFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_privada:
                service.nuevoUrl=putUrl("E. Privada");
                fragmentList = new NoticiasFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_universidad:
                service.nuevoUrl=putUrl("Universidad");
                fragmentList = new NoticiasFragment();
                esperarYCerrar(seg);
                break;
            case R.id.nav_somos:
                progressDialog.dismiss();
                fragment = new SomosFragment();
                break;
            case R.id.nav_aviso:
                progressDialog.dismiss();
                fragment = new AvisoFragment();
                break;
            case R.id.nav_contacto:
                progressDialog.dismiss();
                fragment = new ContactoFragment();
                break;
            case R.id.nav_afiliate:
                fragment = new AfiliateFragment();
                esperarYCerrar(seg);
                break;
        }

        //replacing the fragment
       if (fragment != null ) {

            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.replace(R.id.content_empty, fragment);
            ft.commit();

       }else if(fragmentList != null){
           FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
           ft.replace(R.id.content_empty, fragmentList);
           ft.commit();
       }

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

    public String putUrl(String categoria){

        String url = "";

        //Cursor c = getContentResolver().query(StatusContract.CONTENT_URI, new String[]{StatusContract.ColumnUrls.IDURL,StatusContract.ColumnUrls.URLCAT,StatusContract.ColumnUrls.CAT},StatusContract.ColumnUrls.CAT + " like ? " , new String[]{categoria}, null);

        if(categoria == "Formación"){
            url = "http://castillayleon.fespugt.es/actividades/formacion?format=feed&type=rss";
        }else if (categoria == "Universidad") {
            url = "http://castillayleon.fespugt.es/sectores/ensenanza/universidad?format=feed&type=rss";
        }else if (categoria == "E. Pública") {
            url = "http://castillayleon.fespugt.es/sectores/ensenanza/e-publica?format=feed&type=rss";
        }else if (categoria == "E. Privada") {
            url = "http://castillayleon.fespugt.es/sectores/ensenanza/e-privada?format=feed&type=rss";
        }

        return url;
    }

}
