package com.rthoni.camotion.ui;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.provider.Settings;
import android.support.design.widget.NavigationView;
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.MenuItem;
import android.view.SubMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.luticate.auth.dbo.LuFullLoginDbo;
import com.luticate.utils.business.LuPromise;
import com.luticate.utils.business.LuRequest;
import com.rthoni.camotion.R;
import com.rthoni.camotion.business.CamotionBusiness;
import com.rthoni.camotion.dbo.LocationDbo;
import com.rthoni.camotion.ui.dialogs.LoginDialog;
import com.rthoni.camotion.ui.fragments.CamerasFragment;
import com.rthoni.camotion.ui.fragments.CamotionFragment;
import com.rthoni.camotion.ui.fragments.CommandsFragment;
import com.rthoni.camotion.ui.fragments.SensorsFragment;

import java.util.List;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private LuFullLoginDbo _fullLoginDbo = null;
    private LocationDbo _currentLocation = null;

    private TextView _locationNameView;
    private SubMenu _locationsMenu;
    private NavigationView _navigationView;

    private static final int REQUEST_CODE_ADD_ACCOUNT = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LuRequest.init(this);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        _locationNameView = (TextView) findViewById(R.id.location_name_textview);

        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.setDrawerListener(toggle);
        toggle.syncState();

        _navigationView = (NavigationView) findViewById(R.id.nav_view);
        _navigationView.setNavigationItemSelectedListener(this);
        _locationsMenu = _navigationView.getMenu().findItem(R.id.location_menu).getSubMenu();

        init();
    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);

    }

    private void init()
    {
        List<LocationDbo> locations = CamotionBusiness.getLocations(MainActivity.this);

        if (locations.isEmpty())
        {
            Intent intent = new Intent(Settings.ACTION_ADD_ACCOUNT);
            intent.putExtra(Settings.EXTRA_AUTHORITIES, new String[]{getResources().getString(R.string.account_type)});
            startActivityForResult(intent, REQUEST_CODE_ADD_ACCOUNT);
            return;
        }

        _locationsMenu.clear();
        if (locations.isEmpty()) {
            return;
        }
        for (final LocationDbo location : locations) {
            MenuItem item = _locationsMenu.add(location.getName());
            item.setIcon(R.mipmap.ic_location);
            item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    setLocation(location);
                    return false;
                }
            });
        }
        // Force drawer update; need a fix
        MenuItem item = _navigationView.getMenu().add("test42");
        _navigationView.getMenu().removeItem(item.getItemId());

        if (_currentLocation == null) {
            setLocation(locations.get(0));
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_ADD_ACCOUNT)
        {
            init();
        }
    }

    private void setLocation(LocationDbo location)
    {
        _currentLocation = location;
        _fullLoginDbo = null;
        _locationNameView.setText(_currentLocation.getName());
        showView(-1);
        LoginDialog dlg = new LoginDialog(this);
        dlg.loginFull(_currentLocation).then(new LuPromise.LuConsumer<LuFullLoginDbo>() {
            @Override
            public void execute(LuFullLoginDbo data) {
                _fullLoginDbo = data;
                showView(getDefaultView());
            }
        }, new LuPromise.LuConsumer<LuPromise.LuPromiseError>() {
            @Override
            public void execute(LuPromise.LuPromiseError error) {
                showView(-1);
                Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
            }
        });
    }

    private int getDefaultView()
    {
        if (_fullLoginDbo != null)
        {
            if (_fullLoginDbo.hasPermission("CAMOTION_CAMERA_GET"))
            {
                return R.id.nav_cameras;
            }
            else if (_fullLoginDbo.hasPermission("CAMOTION_SENSOR_GET"))
            {
                return R.id.nav_sensors;
            }
            else if (_fullLoginDbo.hasPermission("CAMOTION_COMMAND_GET"))
            {
                return R.id.nav_commands;
            }
        }
        return -1;
    }

    private void showView(int view)
    {
        CamotionFragment fragment;
        if (view == R.id.nav_cameras) {
            fragment = new CamerasFragment();
        } else if (view == R.id.nav_sensors) {
            fragment = new SensorsFragment();
        } else if (view == R.id.nav_commands) {
            fragment = new CommandsFragment();
        } /*else if (view == -1) {
            fragment = new DefaultFragment();
        } */else {
            return;
        }
        fragment.setCamotionDbo(_fullLoginDbo, _currentLocation);
        getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
    }

    @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 onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.nav_cameras || id == R.id.nav_sensors || id == R.id.nav_commands) {
            showView(id);
        }

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

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