package com.tylerbrockett.smarthost.UI;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.tylerbrockett.smarthost.DataStorage.Database;
import com.tylerbrockett.smarthost.DataStorage.DbHelper;
import com.tylerbrockett.smarthost.DataStorage.SharedPrefsHelper;
import com.tylerbrockett.smarthost.R;

public class GuestDetails extends AppCompatActivity {

    Typeface tf_quicksand_regular;

    DbHelper db;
    SharedPrefsHelper sp;
    Cursor cursor;

    ImageView gImage;
    TextView gName,
            lPhone, gPhone,
            lEmail, gEmail,
            lAddress, gAddress,
            lRsvp,
            lNotes, gNotes,
            btnSpaceEmail, btnSpacePhone, btnSpaceSms;
    Spinner gRsvp;
    ImageButton smsButton, emailButton, phoneButton, editButton, closeButton;

    int g_id;
    String e_name;

    LoadDetailsTask loadDetails;

    Uri default_image;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        setContentView(R.layout.ui_guest_details);

        g_id = getIntent().getIntExtra(Database.G_ID, -1);
        if(g_id < 0){
            Toast.makeText(this, "ERROR: Invalid Guest ID.", Toast.LENGTH_SHORT).show();
            finish();
        }

        default_image = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE +
                "://" + getResources().getResourcePackageName(R.drawable.default_contact_image_1) +
                '/' + getResources().getResourceTypeName(R.drawable.default_contact_image_1) +
                '/' + getResources().getResourceEntryName(R.drawable.default_contact_image_1) );


        db = DbHelper.getHelper(this);
        sp = new SharedPrefsHelper(this);

        // General UI setup.
        setUpResources();
        setUpUIElements();

    }

    @Override
    public void onResume() {
        super.onResume();
        loadDetails = new LoadDetailsTask();
        loadDetails.execute();
    }

    @Override
    public void onPause() {
        super.onPause();

    }

    /* General setup of UI. All elements/widgets are instantiated.*/
    private void setUpUIElements(){
        gImage = (ImageView)findViewById(R.id.contact_image);
        gName = (TextView)findViewById(R.id.guest_name);
        lPhone = (TextView)findViewById(R.id.label_phone);
        gPhone = (TextView)findViewById(R.id.guest_phone);
        lEmail = (TextView)findViewById(R.id.label_email);
        gEmail = (TextView)findViewById(R.id.guest_email);
        lAddress = (TextView)findViewById(R.id.label_address);
        gAddress = (TextView)findViewById(R.id.guest_address);
        lRsvp = (TextView)findViewById(R.id.label_rsvp);
        gRsvp = (Spinner)findViewById(R.id.guest_rsvp);
        lNotes = (TextView)findViewById(R.id.label_notes);
        gNotes = (TextView)findViewById(R.id.guest_notes);
        btnSpaceEmail = (TextView)findViewById(R.id.email_button_space);
        btnSpacePhone = (TextView)findViewById(R.id.phone_button_space);
        btnSpaceSms = (TextView)findViewById(R.id.sms_button_space);
        smsButton = (ImageButton)findViewById(R.id.sms_button);
        phoneButton = (ImageButton)findViewById(R.id.phone_button);
        emailButton = (ImageButton)findViewById(R.id.email_button);
        editButton = (ImageButton)findViewById(R.id.edit_button);
        closeButton = (ImageButton)findViewById(R.id.close_button);
            gName.setTypeface(tf_quicksand_regular);
            lPhone.setTypeface(tf_quicksand_regular);
            gPhone.setTypeface(tf_quicksand_regular);
            lEmail.setTypeface(tf_quicksand_regular);
            gEmail.setTypeface(tf_quicksand_regular);
            lAddress.setTypeface(tf_quicksand_regular);
            gAddress.setTypeface(tf_quicksand_regular);
            lRsvp.setTypeface(tf_quicksand_regular);
            lNotes.setTypeface(tf_quicksand_regular);
            gNotes.setTypeface(tf_quicksand_regular);

        String[] items = new String[]{
                getString(R.string.rsvp_notsent),
                getString(R.string.rsvp_sent),
                getString(R.string.rsvp_coming),
                getString(R.string.rsvp_notcoming)
        };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
        gRsvp.setAdapter(adapter);

    }

    private void setUpResources(){
        tf_quicksand_regular = Typeface.createFromAsset(getAssets(), "quicksand_regular.otf");
    }

    private void update(){
        if(cursor.moveToFirst()){

            String name = cursor.getString(Database.COLUMN_GUEST_NAME);
            final String phone = cursor.getString(Database.COLUMN_GUEST_PHONE);
            final String email = cursor.getString(Database.COLUMN_GUEST_EMAIL);
            String address = cursor.getString(Database.COLUMN_GUEST_ADDRESS);
            int rsvpSelected = cursor.getInt(Database.COLUMN_GUEST_RSVP);
            String notes = cursor.getString(Database.COLUMN_GUEST_NOTES);
            String image_uri = cursor.getString(Database.COLUMN_GUEST_IMAGE_URI);

            gName.setText(name);
            gPhone.setText(phone);
            gEmail.setText(email);
            gAddress.setText(address);
            gRsvp.setSelection(rsvpSelected);
            gNotes.setText(notes);

            if(phone.isEmpty()){
                phoneButton.setVisibility(View.GONE);
                btnSpacePhone.setVisibility(View.GONE);
                smsButton.setVisibility(View.GONE);
                btnSpaceSms.setVisibility(View.GONE);
                gPhone.setVisibility(View.GONE);
                lPhone.setVisibility(View.GONE);
            }
            else{
                phoneButton.setVisibility(View.VISIBLE);
                btnSpacePhone.setVisibility(View.VISIBLE);
                smsButton.setVisibility(View.VISIBLE);
                btnSpaceSms.setVisibility(View.VISIBLE);
                gPhone.setVisibility(View.VISIBLE);
                lPhone.setVisibility(View.VISIBLE);
            }

            if(email.isEmpty()){
                emailButton.setVisibility(View.GONE);
                btnSpaceEmail.setVisibility(View.GONE);
                gEmail.setVisibility(View.GONE);
                lEmail.setVisibility(View.GONE);
            }
            else{
                emailButton.setVisibility(View.VISIBLE);
                btnSpaceEmail.setVisibility(View.VISIBLE);
                gEmail.setVisibility(View.VISIBLE);
                lEmail.setVisibility(View.VISIBLE);
            }

            if(address.isEmpty()){
                gAddress.setVisibility(View.GONE);
                lAddress.setVisibility(View.GONE);
            }
            else{
                gAddress.setVisibility(View.VISIBLE);
                lAddress.setVisibility(View.VISIBLE);
            }

            if(notes.isEmpty()){
                gNotes.setVisibility(View.GONE);
                lNotes.setVisibility(View.GONE);
            }
            else{
                gNotes.setVisibility(View.VISIBLE);
                lNotes.setVisibility(View.VISIBLE);
            }

            Uri image = null;
            if (image_uri != null) {
                image = Uri.parse(image_uri);
            }
            if(image != null){
                try{
                    gImage.setImageURI(image);
                }
                // Hopefully catches when user imports contact (which sets image)
                // and then the contact itself (and the image) is deleted, and
                // setImageURI tries to access that image still...
                // This will reset it to null.
                catch(Exception e){
                    gImage.setImageURI(default_image);
                    ContentValues cv = new ContentValues();
                    cv.put(Database.KEY_GUEST_IMAGE_URI, (String) null);
                    db.updateGuestData(cursor.getInt(Database.COLUMN_DEFAULT_ID), cv);
                }
            }
            else{
                gImage.setImageURI(default_image);
            }

            /* Set On Item Click/Selected Listeners. These are NOT put in it's own method for
            * the sake of not having to have a class variable for each item, and also so that
            * we don't have to query the cursor every time. */

            phoneButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        intent.setData(Uri.parse("tel:" + phone));
                        v.getContext().startActivity(intent);
                    }
                    catch(android.content.ActivityNotFoundException e){
                        Toast.makeText(GuestDetails.this, "No app can handle this request.", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            smsButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try{
                        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone));
                        intent.putExtra("address", phone);
                        intent.putExtra("sms_body",/* Message Body Here*/"");
                        intent.putExtra("compose_mode", true);
                        v.getContext().startActivity(intent);
                    }
                    catch(android.content.ActivityNotFoundException e){
                        Toast.makeText(GuestDetails.this, "No app can handle this request.", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            emailButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        Intent intent = new Intent(android.content.Intent.ACTION_SEND);
                        intent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{});
                        intent.putExtra(android.content.Intent.EXTRA_SUBJECT, e_name);
                        intent.putExtra(android.content.Intent.EXTRA_TEXT, "");
                        intent.putExtra(Intent.EXTRA_EMAIL, new String[]{email});
                        intent.setType("message/rfc822");
                        v.getContext().startActivity(intent);
                    }
                    catch(android.content.ActivityNotFoundException e){
                        Toast.makeText(GuestDetails.this, "No app can handle this request.", Toast.LENGTH_SHORT).show();
                    }
                }
            });

            gRsvp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    if (g_id >= 0) {
                        ContentValues cv = new ContentValues();
                        cv.put(Database.KEY_GUEST_RSVP, position);
                        db.updateGuestData(g_id, cv);
                    } else {
                        Toast.makeText(GuestDetails.this, "Update Failed. Invalid Guest ID.", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {

                }
            });

            editButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent("com.tylerbrockett.smarthost.UI.EditGuest");
                    intent.putExtra(Database.G_ID, g_id);
                    startActivity(intent);
                }
            });

            closeButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(loadDetails != null){
                        loadDetails.cancel(true);
                    }
                    finish();
                }
            });
        }
        else{
            Toast.makeText(this, "ERROR: Invalid Guest ID.", Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    private class LoadDetailsTask extends AsyncTask<Object, Object, Void> {
        @Override
        protected Void doInBackground(Object... params) {
            e_name = "INVALID EVENT NAME";
            if(g_id >= 0){
                cursor = db.rawQuery("SELECT * FROM " + Database.TABLE_GUESTS + " WHERE " + Database.DEFAULT_ID + " = " + g_id);
                if(cursor.moveToFirst()) {
                    long e_id = cursor.getLong(Database.COLUMN_E_ID);
                    Cursor eventCursor = db.rawQuery("SELECT * FROM " + Database.TABLE_EVENTS + " WHERE " + Database.DEFAULT_ID + " = " + e_id);
                    if (eventCursor.moveToFirst()) {
                        e_name = eventCursor.getString(Database.COLUMN_EVENT_NAME);
                    }
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void object) {
            update();
        }
    }
}
