/*
 * This file is part of ZSE Info.
 *
 *     ZSE Info is free software; you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation; either version 3 of the License, or
 *     any later version.
 *
 *     ZSE Info is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 *
 *     You should have received a copy of the GNU General Public License
 *     along with Foobar; if not, write to the Free Software
 *     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

package org.enbyted.android.zseinfo.view.activity;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import org.enbyted.android.zseinfo.InfoApp;
import org.enbyted.android.zseinfo.R;
import org.enbyted.android.zseinfo.data.SynchroniseService;
import org.enbyted.android.zseinfo.data.configuration.Configuration;
import org.enbyted.android.zseinfo.data.synchronise.SyncAdapter;
import org.enbyted.android.zseinfo.view.Notifiable;
import org.enbyted.android.zseinfo.view.NotificationManager;
import org.enbyted.android.zseinfo.view.section.BaseSection;
import org.enbyted.android.zseinfo.view.section.LuckySection;
import org.enbyted.android.zseinfo.view.section.ReplacementsSection;
import org.enbyted.android.zseinfo.view.section.SectionsPagerAdapter;
import org.enbyted.android.zseinfo.view.section.TimetableSection;

/**
 * Created by Bartosz Grabias on 24.02.14.
 */
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener, Notifiable {
    //Synchronise account, etc.
    public static final String AUTHORITY = "org.enbyted.android.zseinfo.provider";
    public static final String ACCOUNT_TYPE = "zseinfo";
    public static final String ACCOUNT = "school";
    private Account account;

    private SectionsPagerAdapter pagerAdapter;
    private ViewPager pager;
    private Menu menu;

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if(action != null && action.equals(SyncAdapter.SYNC_FINISHED)) {
                System.err.println("SYNCED!");
                boolean autoSync = intent.getBooleanExtra("auto", false);

                if(intent.getBooleanExtra("dataChanged", false)) {
                    SynchroniseService.instance().refreshCache();
                    InfoApp.getContext().notifyDataChanged();
                }

                if(intent.getBooleanExtra("configChanged", false))
                    InfoApp.getContext().notifyConfigChanged();

                if(! autoSync) {
                    Toast.makeText(InfoApp.getContext(), "Synchronizacja zakończona.", Toast.LENGTH_LONG).show();
                }
            }
        }
    };

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

        InfoApp.setActivity(this);

        final ActionBar actionBar = getSupportActionBar();

        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Set up the ViewPager with the sections adapter.
        pager = (ViewPager) findViewById(R.id.pager);

        pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(pagerAdapter);
        pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
                InfoApp.getContext().notifyUiChanged();
            }
        });

        addSection(new TimetableSection());
        addSection(new ReplacementsSection());
        addSection(new LuckySection());

        //Synchronise stuff

        account = createSyncAccount(this);
        ContentResolver.addPeriodicSync(
                account,
                AUTHORITY,
                new Bundle(),
                180
        );


//        ContentResolver.setMasterSyncAutomatically(true);

        //

        Configuration.getInstance().init();
    }

    public static Account createSyncAccount(Context context) {
        Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE);
        AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);

        if(accountManager.addAccountExplicitly(newAccount, null, null)) {
            ContentResolver.setSyncAutomatically(
                    newAccount,
                    AUTHORITY,
                    true
            );
            ContentResolver.setIsSyncable(
                    newAccount,
                    AUTHORITY,
                    1
            );
        } else {

        }
        return newAccount;
    }


    @Override
    protected void onPause() {
        super.onPause();
        InfoApp.getContext().setInFront(false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        InfoApp.getContext().setInFront(true);
        InfoApp.getContext().notifyConfigChanged();
        InfoApp.getContext().notifyDataChanged();

        Intent intent = getIntent();
        String tab;
        if(intent != null) {
            if(intent.hasExtra("TYPE"))
                NotificationManager.removeNotify(intent.getIntExtra("TYPE", 0));

            if((tab = intent.getStringExtra("tab")) != null) {
//                InfoApp.getContext().notifyConfigChanged();
//                InfoApp.getContext().notifyDataChanged();
                switch(tab) {
                    case "TAB_REPLACEMENTS": {
                        getSupportActionBar().setSelectedNavigationItem(1);
                        if(intent.getBooleanExtra("my_class", false)) {
                            ((ReplacementsSection)pagerAdapter.getSection(1)).showMyClass();
                        }
                        break;
                    }
                }
            }
            intent.replaceExtras(new Bundle());
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        registerReceiver(broadcastReceiver, new IntentFilter(SyncAdapter.SYNC_FINISHED));
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(broadcastReceiver);
    }

    private void addSection(BaseSection section) {
        pagerAdapter.addSection(section);
        getSupportActionBar().addTab(
                getSupportActionBar().newTab()
                        .setText(section.getTitle())
                        .setTabListener(this));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        BaseSection currentSection = pagerAdapter.getSection(getSupportActionBar().getSelectedTab().getPosition());
        if(keyCode == KeyEvent.KEYCODE_BACK && currentSection.isBackActive()) {
            currentSection.onBackPressed();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //Notify system stuff

    @Override
    public void notifyUiChanged() {
        if(menu != null) {
            BaseSection currentSection = pagerAdapter.getSection(getSupportActionBar().getSelectedTab().getPosition());
            MenuItem menuItem = menu.findItem(R.id.action_refresh);
            if(menuItem != null) menuItem.setVisible(currentSection.isRefreshActive());
            getSupportActionBar().setDisplayHomeAsUpEnabled(currentSection.isBackActive());
        }
    }

    @Override
    public void notifyConfigChanged() {
        pagerAdapter.invalidate();
    }

    @Override
    public void notifyDataChanged() {

    }

    //Menu and navigation stuff

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.menu = menu;
        getMenuInflater().inflate(R.menu.timetable, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        BaseSection currentSection = pagerAdapter.getSection(getSupportActionBar().getSelectedTab().getPosition());
        switch (item.getItemId()) {
            case R.id.action_refresh: {
                if(currentSection.isRefreshActive()) {
                    currentSection.onRefreshPressed();
                }
                break;
            }
            case android.R.id.home: {
                if(currentSection.isBackActive()) {
                    currentSection.onBackPressed();
                }
                break;
            }
            case R.id.action_settings: {
                Intent intent = new Intent(this, SettingsActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.action_about: {
                Intent intent = new Intent(this, AboutActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.action_synchronise: {
                Toast.makeText(this, "Rozpoczynanie synchronizacji.", Toast.LENGTH_LONG).show();

                Bundle extras = new Bundle();
                extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
                extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
                extras.putBoolean("config", true);
                extras.putBoolean("replacements", true);
                extras.putBoolean("timetables", true);


                ContentResolver.requestSync(account, AUTHORITY, extras);
                break;
            }
        }

        return false;
    }

    //Tab stuff

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        pager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {

    }

}
