package community.peers.internetradio.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.HashMap;

import community.peers.internetradio.fragment.StationsFragment;
import community.peers.internetradio.fragment.PlayedFragment;
import community.peers.internetradio.R;
import community.peers.internetradio.network.Player;
import community.peers.internetradio.storage.Settings;

public  class MainActivity
        extends AppCompatActivity
{
    /**
     * Used as callback from fragments when clicking an item,
     * to upload the list of last played radios.
     */
    public interface StationListItem
    {
        // Start streaming
        void stream (HashMap<String, String> aRadio);
    }

    protected Toolbar toolbar;
    protected TabLayout tabLayout;
    protected ViewPager viewPager;
    protected Menu appMenu;
    protected EditText layout_search_box;
    protected boolean search_box_open = false;

    protected StationsFragment myStationsFragment;
    protected PlayedFragment myPlayedFragment;

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

        // Get references to view objects
        this.layout_search_box = (EditText) findViewById(R.id.search_box);

        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        this.setSupportActionBar(toolbar);

        this.viewPager = (ViewPager) findViewById(R.id.viewpager);
        this.setupViewPager(this.viewPager);

        this.tabLayout = (TabLayout) findViewById(R.id.tabs);
        this.tabLayout.setupWithViewPager(this.viewPager);

        // Autoplay if autoplay is ON
        this.autoplay();

        // Click handler for "Now playing" toolbar
        ((LinearLayout) this.findViewById(R.id.playing_info)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Player.playOrPause();
            }
        });

        // Long-Click handler for "Now playing" toolbar
        ((LinearLayout) this.findViewById(R.id.playing_info)).setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v)
            {
                Player.stop();

                // https://developer.android.com/reference/android/view/View.OnLongClickListener.html#onLongClick%28android.view.View%29
                return true;
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.app_menu, menu);

        this.appMenu = menu;

        // Back button
        //getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Action bar title and logo
        getSupportActionBar().setDisplayShowHomeEnabled (true);
        getSupportActionBar().setDisplayUseLogoEnabled (true);
        // getSupportActionBar().setLogo (R.drawable.logo);
        //getSupportActionBar().setTitle("");

        // Set checkbox for menu item (autoplay)
        this.appMenu.findItem (R.id.menu_item_autoplay)
            .setChecked (Settings.autoplay (this));

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId())
        {
            case R.id.menu_item_search:
                this.toggleSearchBar ();
                return true;
            case R.id.menu_item_autoplay:
                this.toggleAutoplay ();
                return true;
            case R.id.menu_item_about:
                showAboutPage ();
                return true;
            case R.id.menu_item_clear_list:
                Settings.emptyLastPlayedList(this);
                myPlayedFragment.loadLastPlayed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    // Setup tab pages
    protected void setupViewPager(ViewPager viewPager)
    {
        // Adapter for the page tabs
        ViewPagerAdapter adapter = new ViewPagerAdapter(this.getSupportFragmentManager());
        final Activity activityContext = this;

        StationListItem clickCallback = new StationListItem() {
            @Override
            public void stream(HashMap<String, String> aRadio)
            {
                Player.playStream(activityContext, aRadio);

                // Save radio to list of last played
                Settings.addNewPlayedRadio(activityContext, aRadio);

                // Reload last played radios in fragment
                myPlayedFragment.loadLastPlayed();
            }
        };

        this.myStationsFragment = new StationsFragment();
        this.myPlayedFragment = new PlayedFragment();

        this.myStationsFragment.setClickCallback(clickCallback);
        this.myPlayedFragment.setClickCallback(clickCallback);

        adapter.addFragment(this.myStationsFragment, getString(R.string.stations));
        adapter.addFragment(this.myPlayedFragment, getString(R.string.last_played));

        viewPager.setAdapter(adapter);
    }

    // Hide/Show search bar
    void toggleSearchBar ()
    {
        // Searching will be done in the actionbar.
        ActionBar action = this.getSupportActionBar();

        if (search_box_open) {
            // Close the search or delete the search query.
            if (layout_search_box.getText().toString().equals("")) {
                action.setDisplayShowCustomEnabled(true);

                // Change search icon from X to lens.
                this.appMenu
                        .findItem(R.id.menu_item_search)
                        .setIcon(ContextCompat.getDrawable(this, R.drawable.ic_search_dark));

                // Remove keyboard
                unfocusSearchBox ();

                // Remove the search view and display the title again.
                action.setCustomView(null);
                action.setDisplayShowTitleEnabled(true);

                // Keep track that the search box is now closed.
                search_box_open = false;
            } else {
                layout_search_box.setText("");
            }
        } else {
            // Replace the title with a search bar.
            action.setDisplayShowCustomEnabled(true);
            action.setDisplayShowTitleEnabled(false);
            action.setCustomView(R.layout.search_bar);

            layout_search_box = (EditText) findViewById (R.id.search_box);
            layout_search_box.addTextChangedListener(new TextWatcher() {
                @Override
                public void afterTextChanged(Editable s) {
                    myStationsFragment.search(layout_search_box.getText().toString());
                }

                @Override
                public void beforeTextChanged(CharSequence cs, int s, int b, int c) {
                }

                @Override
                public void onTextChanged(CharSequence cs, int s, int b, int c) {
                }
            });
            this.focusSearchBox ();

            // Change icon from lens to X.
            this.appMenu
                    .findItem(R.id.menu_item_search)
                    .setIcon(ContextCompat.getDrawable(this, R.drawable.ic_close_dark));

            // Keep track that the search box is now open
            search_box_open = true;
        }
    }

    // Enable/Disable autoplay
    void toggleAutoplay ()
    {
        // Store the new setting
        Settings.toggleAutoplay (this);

        // Update menu checkbox
        this.appMenu.findItem (R.id.menu_item_autoplay)
            .setChecked (Settings.autoplay (this));
    }

    // Move focus to search bar
    void focusSearchBox ()
    {
        layout_search_box.requestFocus ();

        // These lines open the keyboard
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(this.layout_search_box, InputMethodManager.SHOW_IMPLICIT);
    }

    // Lose focus on search bar
    void unfocusSearchBox ()
    {
        // These lines close the keyboard
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(this.layout_search_box.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    // Start a new Activity to display About page
    void showAboutPage ()
    {
        Intent intent = new Intent (this, AboutActivity.class);
        startActivity (intent);
    }

    // Autoplay when app is launched
    void autoplay ()
    {
        // Autoplay disabled
        if (!Settings.autoplay(this))
            return;

        // Get the most recent played station
        ArrayList<HashMap<String, String>> last_played_stations =
            Settings.retrieveLastPlayed(this);

        // The list is empty. Don't play anything
        if (last_played_stations.size() == 0)
            return;

        // Autoplay the radio station that was played last
        Player.playStream(this, last_played_stations.get (0));
    }
}