package com.davidservin.alexa.activities;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;

import com.davidservin.alexa.R;
import com.davidservin.alexa.adapters.ProviderAdapter;
import com.davidservin.alexa.db.InventoryDBHelper;
import com.davidservin.alexa.db.Provider;

public class InventoryProvidersActivity extends AppCompatActivity {

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

        InventoryDBHelper mDbHelper = new InventoryDBHelper(this);
        SQLiteDatabase db = mDbHelper.getWritableDatabase();

        String[] columns = {
                Provider._ID,
                Provider.NAME,
                Provider.PHONE,
                Provider.EMAIL,
        };

        String sort = Provider.NAME + " ASC";

        Cursor c = db.query(Provider.TABLE, columns, null, null, null, null, sort);
        if(c.getCount() > 0) {
            ListView list = (ListView) findViewById(R.id.inventory_providers_list);
            ProviderAdapter adapter = new ProviderAdapter(this, c);
            if (list != null)
                list.setAdapter(adapter);
        } else {
            findViewById(R.id.inventory_providers_empty).setVisibility(View.VISIBLE);
            c.close();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.inventory_providers_menu, menu);
        Drawable drawable = menu.findItem(R.id.inventory_providers_menu_add).getIcon();
        if (drawable != null) {
            drawable.mutate();
            drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.inventory_providers_menu_add:
                Intent intent = new Intent(this, ProviderActivity.class);
                intent.putExtra("newProvider", true);
                startActivity(intent);
                finish();
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
}