package cloud.hmml.mmw;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;

import java.io.IOException;
import java.util.List;

import static android.view.Menu.NONE;

public class ThemePickerActivity extends AppCompatActivity {
    static final int CMENU_APPLY = 1;
    static final int CMENU_DELETE = 2;

    private ListView mListView;

    static public class ThemeAdapter extends ArrayAdapter {
        public ThemeAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List<Theme> themes) {
            super(context, resource, themes);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final Theme theme = (Theme) getItem(position);

            // Check if an existing view is being reused, otherwise inflate the view
            if (convertView == null) {
                convertView = LayoutInflater.from(getContext()).inflate(R.layout.theme_item, parent, false);
            }

            // Lookup view for data population
            TextView name    = (TextView) convertView.findViewById(R.id.theme_name);
            TextView author  = (TextView) convertView.findViewById(R.id.theme_author);
            TextView desc    = (TextView) convertView.findViewById(R.id.theme_desc);
            ImageView image1 = (ImageView) convertView.findViewById(R.id.theme_image1);
            ImageView image2 = (ImageView) convertView.findViewById(R.id.theme_image2);
            ImageView image3 = (ImageView) convertView.findViewById(R.id.theme_image3);
            ImageView image4 = (ImageView) convertView.findViewById(R.id.theme_image4);


            // Populate the data into the template view using the data object
            name.setText(theme.getName());
            author.setText(theme.getAuthor());
            desc.setText(theme.getShortDesc());
            image1.setImageDrawable(null);
            image2.setImageDrawable(null);
            image3.setImageDrawable(null);
            image4.setImageDrawable(null);
            ImageLoader imageLoader = ImageLoader.getInstance();
            imageLoader.displayImage(theme.getIconURL(Theme.W_CLEAR_D), image1);
            imageLoader.displayImage(theme.getIconURL(Theme.W_CLEAR_D + Theme.W_RAIN), image2);
            imageLoader.displayImage(theme.getIconURL(Theme.W_SNOW + Theme.W_CLEAR_N), image3);
            imageLoader.displayImage(theme.getIconURL(Theme.W_CLOUD + Theme.W_THUNDER), image4);

            Drawable bg;
            if (theme.day_frame != null && theme.day_frame.equals("builtin/white")) {
                bg = ContextCompat.getDrawable(getContext(), R.drawable.day_frame_white);
            } else {
                bg = ContextCompat.getDrawable(getContext(), R.drawable.day_frame_black);
            }
            image1.setBackground(bg);
            image2.setBackground(bg);
            image3.setBackground(bg);
            image4.setBackground(bg);

            if (theme.getUri() != null) {
                author.setTextColor(Color.BLUE);
                author.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent i = new Intent(Intent.ACTION_VIEW, theme.getUri());
                        getContext().startActivity(i);
                    }
                });
            }

            // Return the completed view to render on screen
            return convertView;
        }
    }

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

        FloatingActionButton to_download = (FloatingActionButton) findViewById(R.id.btn_to_download);
        to_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(ThemePickerActivity.this, ThemeDownloadActivity.class));
            }
        });

        mListView = (ListView) findViewById(R.id.cur_theme_list);
        mListView.setAdapter(new ThemeAdapter(this, R.layout.theme_item, Theme.getAll(this)));
        mListView.setOnItemClickListener(new ListView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.d("theme-picker", "theme picked position: "+position);
                Intent i = new Intent();
                Theme theme = (Theme) parent.getItemAtPosition(position);
                i.putExtra("TYPE", theme.getType());
                i.putExtra("ID", theme.getId());
                setResult(RESULT_OK, i);
                finish();
            }
        });
        registerForContextMenu(mListView);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshList();
    }

    protected void refreshList() {
        ArrayAdapter adapter = (ArrayAdapter) mListView.getAdapter();
        adapter.clear();
        adapter.addAll(Theme.getAll(this));
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo info) {
        super.onCreateContextMenu(menu, view, info);
        if (mListView == view) {
            Theme theme = (Theme) mListView.getItemAtPosition(((AdapterView.AdapterContextMenuInfo) info).position);
            menu.setHeaderTitle(theme.getName());
            menu.add(NONE, CMENU_APPLY, NONE, R.string.apply_this_theme);
            if (theme.getType() == Theme.TYPE_IN_STORAGE)
                menu.add(NONE, CMENU_DELETE, NONE, R.string.delete_theme);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        super.onContextItemSelected(item);
        Theme theme = (Theme) mListView.getItemAtPosition(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);
        if (item.getItemId() == CMENU_APPLY) {
            Intent i = new Intent();
            i.putExtra("TYPE", theme.getType());
            i.putExtra("ID", theme.getId());
            setResult(RESULT_OK, i);
            finish();
        } else if (item.getItemId() == CMENU_DELETE) {
            ArrayAdapter adapter = (ArrayAdapter) mListView.getAdapter();
            try {
                theme.delete();
                adapter.remove(theme);
                adapter.notifyDataSetChanged();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
