package com.dushantsw.stockholmbostad.view.activities;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.dushantsw.stockholmbostad.R;
import com.dushantsw.stockholmbostad.integration.sqlite.AdListStore;
import com.dushantsw.stockholmbostad.model.Filter;
import com.dushantsw.stockholmbostad.model.HousingAd;
import com.dushantsw.stockholmbostad.model.NotificationBuilder;
import com.dushantsw.stockholmbostad.model.SortingOption;
import com.dushantsw.stockholmbostad.view.adapters.AdsAdapter;
import com.dushantsw.stockholmbostad.view.adapters.SortOptionsAdapter;
import com.dushantsw.stockholmbostad.view.services.AdAlarmEventReceiver;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

public class StartActivity extends AppCompatActivity {
    private static final String TAG = "StartActivity";
    private static final int REQUEST_FILTER_AD = 2005;
    private static final int REQUEST_FILTER_NOTIFICATION = 2006;
    public static final String EXTRAS_ADS = "extras-ads";

    private AdListStore mListStore;

    private DrawerLayout mDrawerLayout;
    private AdsAdapter mAdsAdapter;
    private SortOptionsAdapter mSortOptionsAdapter;

    private Context mContext;
    private TextView numberOfAdsTextView;

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

        // Initialize text views
        numberOfAdsTextView = (TextView) findViewById(R.id.activity_start_number_of_ads_text_view);
        mContext = this;
        mListStore = new AdListStore(mContext);

        // Setup drawer
        setupDrawer();

        // Setup list view
        setupAdsListView();

        // Set action bar title
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setTitle(R.string.title_start);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.main_menu_notification:
                goToFilterActivity(REQUEST_FILTER_NOTIFICATION);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void setupAdsListView() {
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            List<HousingAd> ads = extras.getParcelableArrayList(EXTRAS_ADS);
            if (ads != null && !ads.isEmpty()) {
                int totalAvailableHouses = 0;
                for (HousingAd ad : ads) {
                    totalAvailableHouses += ad.getNumberOfHouses();
                    mListStore.addNewAd(ad.getId(), ad.getAdFrom());
                }

                // Setup list view
                ListView mAdsListView = (ListView) findViewById(R.id.ads_list_view);

                // Load ads
                numberOfAdsTextView.setText(String.format(Locale.getDefault(), "%d", totalAvailableHouses));
                mAdsListView.setAdapter(mAdsAdapter = new AdsAdapter(mContext, ads));
                mAdsListView.setOnItemClickListener(new StartActivity.AdOnItemClickListener());

                // Sort ads to latest
                mAdsAdapter.sortAds(SortingOption.LATEST);
                mSortOptionsAdapter.setCurrentSortOption(SortingOption.LATEST);

                // Test notification remove
                new NotificationBuilder(mContext, new ArrayList<>(ads.subList(5, 10))).build();
            }
        }
    }

    private void setupDrawer() {
        mDrawerLayout = (DrawerLayout) findViewById(R.id.main_drawer_layout);
        ListView sortDrawerList = (ListView) findViewById(R.id.sort_drawer);

        String[] optionsArray = getResources().getStringArray(R.array.sort_options);
        List<String> options = Arrays.asList(optionsArray);
        mSortOptionsAdapter = new SortOptionsAdapter(mContext, options);

        sortDrawerList.setAdapter(mSortOptionsAdapter);
        sortDrawerList.setOnItemClickListener(new DrawerOnItemClickListener());
    }

    public void onFilterAdsTapped(View view) {
        goToFilterActivity(REQUEST_FILTER_AD);
    }

    private void goToFilterActivity(int requestCode) {
        Intent intent = new Intent(this, FilterActivity.class);
        if (mAdsAdapter.getCurrentFilter() != null)
            intent.putExtra(FilterActivity.FILTER, mAdsAdapter.getCurrentFilter());
        startActivityForResult(intent, requestCode);
    }

    public void onSortAdsTapped(View view) {
        mDrawerLayout.openDrawer(GravityCompat.END, true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_FILTER_AD || requestCode == REQUEST_FILTER_NOTIFICATION) {
                final Filter filter = (Filter) data.getExtras().get(FilterActivity.FILTER);

                if (filter != null) {
                    if (requestCode == REQUEST_FILTER_AD) {
                        int numberOfHouses = mAdsAdapter.filterAds(filter);
                        numberOfAdsTextView.setText(
                                String.format(Locale.getDefault(), "%d", numberOfHouses));
                    } else {
                        try {
                            filter.storeIntoSharedPreferences(mContext);
                        } catch (JSONException e) {
                            Log.e(TAG, "Could not parse json from filter object");
                        }

                        // Start cron job
                        AdAlarmEventReceiver.setupCronJob(mContext);

                        Toast.makeText(mContext,
                                getString(R.string.alarm_set), Toast.LENGTH_LONG).show();
                    }
                }
            }
        }
    }


    private class DrawerOnItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SortingOption option = SortingOption.values()[position];
            mAdsAdapter.sortAds(option);

            // Call sorting adapter to change current sort option.
            mSortOptionsAdapter.setCurrentSortOption(option);
        }
    }

    private class AdOnItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            HousingAd housingAd = (HousingAd) mAdsAdapter.getItem(position);
            Log.i(TAG, "Ad nr " + housingAd.getId() + " has been clicked ");

            Intent intent = new Intent(mContext, DetailsActivity.class);
            intent.putExtra(DetailsActivity.EXTRAS_AD, housingAd);
            startActivity(intent);
        }
    }
}
