package com.ztone.musicplayer.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ztone.musicplayer.GlobalVariable.GlobalVariable;
import com.ztone.musicplayer.R;
import com.ztone.musicplayer.adapter.MainFragmentAdapter;
import com.ztone.musicplayer.biz.MusicListBiz;
import com.ztone.musicplayer.biz.PlayListBiz;
import com.ztone.musicplayer.biz.PlayListBizImpl;
import com.ztone.musicplayer.fragments.MusicByAlbum;
import com.ztone.musicplayer.fragments.MusicBySinger;
import com.ztone.musicplayer.fragments.MusicRank;
import com.ztone.musicplayer.fragments.MvFragment;
import com.ztone.musicplayer.fragments.Recommend;
import com.ztone.musicplayer.fragments.SingleMusic;
import com.ztone.musicplayer.po.MusicList;
import com.ztone.musicplayer.po.PlayList;
import com.ztone.musicplayer.service.MusicPlayerService;
import com.ztone.musicplayer.transit.MusicListTransit;

import java.util.ArrayList;
import java.util.List;

import static com.ztone.musicplayer.R.id.list_btn_next;
import static com.ztone.musicplayer.R.id.list_btn_play;
import static com.ztone.musicplayer.R.id.list_btn_prev;

public class MainActivity extends AppCompatActivity implements SingleMusic.OnFragmentInteractionListener,
        MusicBySinger.OnFragmentInteractionListener, MusicByAlbum.OnFragmentInteractionListener, MusicRank.OnFragmentInteractionListener, Recommend.OnFragmentInteractionListener,View.OnClickListener,MvFragment.OnFragmentInteractionListener {

    static final String TAG = "MainActivity";
    private MusicPlayerService musicPlayerService = MusicPlayerService.getMusicPlayerService();
    private GlobalVariable globalVariable;
    private Toolbar toolbar;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private ImageButton toolBarBtn1;
    //private ImageButton toolBarBtn2;
    private ImageButton toolBarBtn3;
    private ImageButton toolBarBtn4;
    private ListView lvLeftMenu;
    private PlayListBiz playListBiz;
    private PlayList playList;
    private String[] lvs = {"扫描本地音乐", "我的消息", "积分商城", "付费音乐包", "在线听歌免流量", "听歌识曲", "主题换肤", "夜间模式", "定时停止播放", "音乐闹钟",
            "我的音乐云盘", "定时停止播放", "音乐闹钟", "我的音乐云盘"};
    private ArrayAdapter arrayAdapter;

    private ViewPager mainViewPager;
    private MainFragmentAdapter adapter;
    private MusicListBiz musicListBiz;
    private Button bt_prev;
    private Button bt_play;
    private Button bt_next;
    private TextView tv_songtitle;
    private TextView tv_songinfo;
    private RelativeLayout opera_layout;
    private ImageView im_Album;

    //广播
    private ExBroadcast ExBroadcastReceiver;
    private IntentFilter intentFilter;
    private LocalBroadcastManager localBroadcastManager;
    private MediaPlayer player;
    private MusicPlayerActivity musicPlayerActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        musicPlayerService.setMainActivity(this);
        globalVariable = (GlobalVariable) getApplication();
        findViews(); //获取控件
        toolbar.setTitle("");//设置Toolbar标题
        toolbar.setTitleTextColor(Color.parseColor("#ffffff")); //设置标题颜色
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.open, R.string.close) {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        mDrawerToggle.syncState();
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        //设置菜单列表
        arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, lvs);






        //广播注册
        ExBroadcastReceiver = new ExBroadcast();
        intentFilter = new IntentFilter();
        intentFilter.addAction("exmusicplayerUI");
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.registerReceiver(ExBroadcastReceiver, intentFilter);

    }

    public void setMusicPlayerActivity(MusicPlayerActivity musicPlayerActivity) {
        this.musicPlayerActivity = musicPlayerActivity;
    }

    public List<Button> getfrgmentButtons() {
        List<Button> lists = new ArrayList<Button>();

        lists.add(bt_prev);
        lists.add(bt_play);
        lists.add(bt_next);
        return lists;

    }

    public List<TextView> getfrgmentTextViews() {
        List<TextView> tv_lists = new ArrayList<TextView>();
        tv_lists.add(tv_songtitle);
        tv_lists.add(tv_songinfo);
        return tv_lists;

    }

    public List<ImageView> getfragmentImageView() {
        List<ImageView> im_lists = new ArrayList<ImageView>();
        im_lists.add(im_Album);
        return im_lists;
    }

    private void findViews() {
        toolbar = (Toolbar) findViewById(R.id.tl_custom);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.dl_left);
        toolBarBtn1 = (ImageButton) findViewById(R.id.toolbar_btn1);
//        toolBarBtn2 = (ImageButton) findViewById(R.id.toolbar_btn2);
        toolBarBtn3 = (ImageButton) findViewById(R.id.toolbar_btn3);
        toolBarBtn4 = (ImageButton) findViewById(R.id.toolbar_btn4);
        toolBarBtn1.setOnClickListener(onClickListener);
//        toolBarBtn2.setOnClickListener(onClickListener);
        toolBarBtn3.setOnClickListener(onClickListener);
        toolBarBtn4.setOnClickListener(onClickListener);
        opera_layout = (RelativeLayout) findViewById(R.id.list_opera_layout);
        opera_layout.setOnClickListener(onClickListener);
        mainViewPager = (ViewPager) findViewById(R.id.mainPager);
        adapter = new MainFragmentAdapter(this.getSupportFragmentManager());
        mainViewPager.setAdapter(adapter);
        mainViewPager.setCurrentItem(0);
        updateToolBarUi(0);
        mainViewPager.setOnPageChangeListener(new MyOnPageChangeListen());
//侧滑组件初始化
        LinearLayout search= (LinearLayout) findViewById(R.id.custom_drawer_item);
        LinearLayout them= (LinearLayout) findViewById(R.id.custom_drawer_item2);
        LinearLayout qusetion= (LinearLayout) findViewById(R.id.custom_drawer_item3);
        LinearLayout about= (LinearLayout) findViewById(R.id.custom_drawer_item4);
        LinearLayout exit= (LinearLayout) findViewById(R.id.custom_drawer_item5);
        search.setOnClickListener(this);
        them.setOnClickListener(this);
        qusetion.setOnClickListener(this);
        about.setOnClickListener(this);
        exit.setOnClickListener(this);
        //下浮窗组件初始化
        im_Album = (ImageView) findViewById(R.id.imageViewAlbum);
        tv_songtitle = (TextView) findViewById(R.id.song_title);
        tv_songinfo = (TextView) findViewById(R.id.song_info);
        bt_prev = (Button) findViewById(list_btn_prev);
        bt_prev.setOnClickListener(onClickListener);
        bt_play = (Button) findViewById(list_btn_play);
        bt_play.setOnClickListener(onClickListener);
        bt_next = (Button) findViewById(list_btn_next);
        bt_next.setOnClickListener(onClickListener);
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent intent;
            switch (i) {
                case 0:
                    MusicListTransit transit = new MusicListTransit();
                    transit.getAllMusic(MainActivity.this);
                    break;
                case 1:
                    GlobalVariable global = (GlobalVariable) getApplication();
                    System.out.println(global.getPlayListList().get(0).getMusicBelongPlayListList().size());
                    System.out.println();
                    PlayListBiz playListBiz = new PlayListBizImpl();
                    List<PlayList> listt = playListBiz.find(MainActivity.this);
//                    System.out.println("directory:"+listt.get(0).getDirectory());
//                    System.out.println();

                    break;
                case 2:
                    playList = new PlayList();
                    playList.setId(0);
                    playList.setPlayListName("我喜欢的音乐");
                    playList.setPlayListImgUrl(String.valueOf(R.drawable.mylikelist));
                    List<MusicList> list = new ArrayList<>();
                    playList.setMusicBelongPlayListList(list);
                    playList.setDirectory("");
                    playListBiz = new PlayListBizImpl();
                    if (playListBiz.add(MainActivity.this, playList)) {
                        Log.i(TAG, "歌单我喜欢的音乐创建成功");
                    } else {
                        Log.i(TAG, "歌单我喜欢的音乐创建失败");
                    }
                    break;
                case 3:
                    GlobalVariable globals = (GlobalVariable) getApplication();
                    playListBiz = new PlayListBizImpl();
                    List<PlayList> lst = playListBiz.find(MainActivity.this);
                    int k = 0;
                    for (k = 0; k < lst.size(); k++) {
                        System.out.println("playId:" + lst.get(k).getId());
                    }
                    lst = globals.getPlayListList();
                    for (k = 0; k < lst.size(); k++) {
                        System.out.println("playId:" + lst.get(k).getId());
                    }
                    break;
                case 4:
                    GlobalVariable globalVariable = (GlobalVariable) getApplication();
                    int h = 0;
                    List<MusicList> musicLists = globalVariable.getMusicListList();
                    for (h = 0; h < musicLists.size(); h++) {
                        System.out.println("musicId:" + musicLists.get(h).getId());
                    }
                    break;
                case 5:
                    GlobalVariable globalVariables = (GlobalVariable) getApplication();
                    int u = 0;
                    for (u = 0; u < globalVariables.getPlayListList().size(); u++) {
                        int y = 0;
                        for (y = 0; y < globalVariables.getPlayListList().get(u).getMusicBelongPlayListList().size(); y++) {

                            System.out.println("playlistImg:" + globalVariables.getPlayListList().get(u).getMusicBelongPlayListList().get(y).getAlbumImgUrl());
                        }
                    }
                    break;
                default:
                    break;

            }
        }
    };

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.toolbar_btn1:
                    updateToolBarUi(0);
                    mainViewPager.setCurrentItem(0);
                    break;
                case R.id.toolbar_btn4:
                    Intent intent1 = new Intent();
                    intent1.setClass(MainActivity.this, SearchActivity.class);
                    startActivity(intent1);
                    break;
                case R.id.toolbar_btn3:
                    updateToolBarUi(2);
                    mainViewPager.setCurrentItem(3);
                    break;
                case R.id.list_opera_layout:
                    if (globalVariable.getMusicPosition() >= 0) {
                        Intent intent = new Intent();
                        intent.setClass(MainActivity.this, MusicPlayerActivity.class);
                        startActivity(intent);
                    } else {
                        Toast.makeText(MainActivity.this, "请选择一首歌", Toast.LENGTH_SHORT).show();
                    }

                    break;
                case list_btn_prev:
                    musicPlayerActivity.previous();
                    break;
                case list_btn_play:
                    if(musicPlayerService.getIsPlaying()){
                        bt_play.setBackgroundResource(R.drawable.list_play_narmal);
                    }else {
                        bt_play.setBackgroundResource(R.drawable.list_pause_normal);
                    }
                    musicPlayerActivity.playOrpause();


                    break;
                case list_btn_next:
                    musicPlayerActivity.next();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
    //侧滑栏点击事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.custom_drawer_item:
                MusicListTransit musicListTransit=new MusicListTransit();
                musicListTransit.getAllMusic(MainActivity.this);
                //  Toast.makeText(MainActivity.this, "点击了", Toast.LENGTH_SHORT).show();
                break;
            case R.id.custom_drawer_item2:
                int i,j;
                GlobalVariable globalVariable = (GlobalVariable) getApplication();
                for (i=0;i<globalVariable.getPlayListList().size();i++){
                    System.out.println("专辑:"+globalVariable.getPlayListList().get(i).getPlayListName());
                    for (j=0;j<globalVariable.getPlayListList().get(i).getMusicBelongPlayListList().size();j++){
                        System.out.println("音乐:"+globalVariable.getPlayListList().get(i).getMusicBelongPlayListList().get(j).getMusicName());
                    }
                }

                break;
            case R.id.custom_drawer_item3:
                Intent intent=new Intent(MainActivity.this,NavDeedBack.class);
                startActivity(intent);
                break;
            case R.id.custom_drawer_item4:
                 intent=new Intent(MainActivity.this,NavAboutActivity.class);
                startActivity(intent);
                break;
            case R.id.custom_drawer_item5:

                final AlertDialog.Builder builder=new AlertDialog.Builder(this);
                builder.setTitle("退出Beat");
                builder.setMessage("真要离开我了吗");
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    }
                });
                  builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialogInterface, int i) {
                          finish();
                          dialogInterface.dismiss();
                      }
                  });
                builder.show();
                break;

        }


    }

    private class MyOnPageChangeListen implements ViewPager.OnPageChangeListener {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            updateToolBarUi(position);

        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    }

    private void updateToolBarUi(int index) {
        switch (index) {
            case 0:
                toolBarBtn1.setBackgroundResource(R.drawable.toolbar_discover_normal);
//                toolBarBtn2.setBackgroundResource(R.drawable.toolbar_music_selected);
                toolBarBtn3.setBackgroundResource(R.drawable.toolbar_music_selected);
                break;
            case 1:
                toolBarBtn1.setBackgroundResource(R.drawable.toolbar_discover_selected);
//                toolBarBtn2.setBaouckgrndResource(R.drawable.toolbar_music_normal);
                toolBarBtn3.setBackgroundResource(R.drawable.toolbar_music_normal);
                break;
            /*case 2:
                toolBarBtn1.setBackgroundResource(R.drawable.toolbar_discover_selected);
//                toolBarBtn2.setBackgroundResource(R.drawable.toolbar_music_selected);
                toolBarBtn3.setBackgroundResource(R.drawable.toolbar_music_normal);
                break;*/
            default:
                break;
        }

    }

    //广播
    class ExBroadcast extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.v("test", "Ex");
            im_Album.setImageBitmap(BitmapFactory.decodeFile(musicPlayerActivity.getTheMusic().getAlbumImgUrl()));
            tv_songinfo.setText(musicPlayerActivity.getTheMusic().getMusicName());
            tv_songtitle.setText(musicPlayerActivity.getTheMusic().getSinger());
        }
    }
}