package ai.pai.client.activity;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.common.utils.DeviceUtils;
import com.android.common.utils.LogHelper;
import com.android.common.utils.TimeUtils;
import com.android.views.indicators.Indicator;
import com.android.views.indicators.IndicatorViewPager;
import com.android.views.indicators.SpringBar;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.sql.Time;

import ai.pai.client.R;
import ai.pai.client.beans.GroupInfo;
import ai.pai.client.db.DBService;
import ai.pai.client.db.Preferences;
import ai.pai.client.fragments.TabMessageFragment;
import ai.pai.client.fragments.TabRecentPhotoFragment;
import ai.pai.client.services.GroupService;
import ai.pai.client.services.MyLocationService;
import ai.pai.client.utils.Constants;
import ai.pai.client.utils.PhotoLoader;
import ai.pai.client.utils.UmengEvent;
import ai.pai.client.views.GroupSelectPopup;
import ai.pai.client.views.PersonInfoPopup;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener, GroupService.GroupServiceListener,IndicatorViewPager.OnIndicatorPageChangeListener {

    private DrawerLayout drawer;
    private Indicator indicator;
    private boolean isBound;
    private GroupServiceConnection serviceConnection;
    private static final int JOIN_REQUEST_CODE = 3002;
    private long exitTime;
    private String guideId;
    private PersonInfoPopup personInfoPopup;
    private ImageButton callGuideBtn;
    private ImageButton gatherBtn;
    private TextView gatherInfoTextView;

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

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        ViewPager viewPager = (ViewPager) findViewById(R.id.spring_viewPager);
        indicator = (Indicator) findViewById(R.id.spring_indicator);
        indicator.setScrollBar(new SpringBar(getApplicationContext(), Color.WHITE));
        viewPager.setOffscreenPageLimit(2);
        IndicatorViewPager indicatorViewPager = new IndicatorViewPager(indicator, viewPager);
        indicatorViewPager.setOnIndicatorPageChangeListener(this);
        indicatorViewPager.setAdapter(adapter);
        indicatorViewPager.setCurrentItem(0, false);

        TextView nicknameTextView = (TextView) navigationView.getHeaderView(0).findViewById(R.id.tv_user_nickname);
        if(Preferences.getInstance(this).isGuestLogin()){
            nicknameTextView.setText(R.string.click_to_login);
        }else{
            nicknameTextView.setText(Preferences.getInstance(this).getNickName());
        }
        ImageView avatar = (ImageView) navigationView.getHeaderView(0).findViewById(R.id.img_user_avatar);
        avatar.setOnClickListener(this);
        nicknameTextView.setOnClickListener(this);
        PhotoLoader.getInstance(this).displayImage(Preferences.getInstance(this).getUserAvatar(), avatar,PhotoLoader.getUserAvatarOptions());
        ImageView drawerToggle = (ImageView) findViewById(R.id.drawer_toggle);
        PhotoLoader.getInstance(this).displayImage(Preferences.getInstance(this).getUserAvatar(), drawerToggle,PhotoLoader.getUserAvatarOptions());
        drawerToggle.setOnClickListener(this);
        gatherInfoTextView = (TextView)findViewById(R.id.tv_gather_info);
        callGuideBtn = (ImageButton)findViewById(R.id.floating_btn_call);
        gatherBtn = (ImageButton)findViewById(R.id.floating_btn_gather);
        findViewById(R.id.floating_btn_add).setOnClickListener(this);
        findViewById(R.id.floating_btn_scan).setOnClickListener(this);
        gatherBtn.setOnClickListener(this);
        callGuideBtn.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        callGuideBtn.setVisibility(TextUtils.isEmpty(Preferences.getInstance(this).getTourGuidePhone()) ? View.INVISIBLE : View.VISIBLE);
        gatherBtn.setVisibility(Preferences.getInstance(this).getGatherTime()<System.currentTimeMillis() ? View.INVISIBLE : View.VISIBLE);
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (isBound) {
            unbindService(serviceConnection);
            serviceConnection = null;
            isBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            if(System.currentTimeMillis()-exitTime<3000){
                super.onBackPressed();
                cleanTmpDirWhenExit();
            }else{
                Toast.makeText(this,R.string.app_exit_hint,Toast.LENGTH_SHORT).show();
            }
            exitTime = System.currentTimeMillis();
        }
    }

    private void cleanTmpDirWhenExit(){
        File tmpDir = new File(Constants.APP_TEMP_DIR);
        if(tmpDir.exists() && tmpDir.listFiles()!=null){
            File[] files = tmpDir.listFiles();
            for(File file : files){
                file.delete();
            }
        }
    }


    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.nav_about_us:
                MobclickAgent.onEvent(this, UmengEvent.slide_about_click);
                startActivity(new Intent(MainActivity.this, AboutUsActivity.class));
                break;
            case R.id.nav_feedback:
                MobclickAgent.onEvent(this, UmengEvent.slide_feedback_click);
                startActivity(new Intent(MainActivity.this, FeedbackActivity.class));
                break;
            case R.id.nav_order_history:
                MobclickAgent.onEvent(this, UmengEvent.slide_order_history_click);
                startActivity(new Intent(MainActivity.this, OrderListActivity.class));
                break;
            case R.id.nav_photo_groups:
                MobclickAgent.onEvent(this, UmengEvent.slide_my_group_click);
                startActivity(new Intent(MainActivity.this, GroupListActivity.class));
                break;
            default:
                break;
        }

        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.floating_btn_gather:
                MobclickAgent.onEvent(this, UmengEvent.home_gather_info_btn_click);
                gatherInfoTextView.setVisibility(gatherInfoTextView.getVisibility()== View.VISIBLE?View.INVISIBLE:View.VISIBLE);
                gatherInfoTextView.setText(getString(R.string.gather_info,TimeUtils.getGatherTimeStr(Preferences.getInstance(this).getGatherTime()),Preferences.getInstance(this).getTourGatherLocation()));
                if(gatherInfoTextView.getVisibility()==View.VISIBLE){
                    gatherInfoTextView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if(gatherInfoTextView!=null && gatherInfoTextView.getContext()!=null){
                                gatherInfoTextView.setVisibility(View.INVISIBLE);
                            }
                        }
                    },3000);
                }
                break;
            case R.id.floating_btn_add:
                MobclickAgent.onEvent(this, UmengEvent.home_new_group_btn_click);
                new GroupSelectPopup(MainActivity.this).showPopupWindow();
                break;
            case R.id.floating_btn_scan:
                MobclickAgent.onEvent(this, UmengEvent.home_scan_btn_click);
                Intent intent = new Intent(MainActivity.this, QRCaptureActivity.class);
                startActivityForResult(intent, JOIN_REQUEST_CODE);
                break;
            case R.id.drawer_toggle:
                if (drawer.isDrawerOpen(GravityCompat.START)) {
                    drawer.closeDrawer(GravityCompat.START);
                } else {
                    drawer.openDrawer(GravityCompat.START);
                }
                break;
            case R.id.tv_user_nickname:
            case R.id.img_user_avatar:
                if(Preferences.getInstance(this).isGuestLogin()){
                    DBService.getInstance(this).clearDB();
                    Preferences.getInstance(this).clearPrefs();
                    startActivity(new Intent(MainActivity.this,GuideActivity.class));
                    finish();
                }else{
                    DBService.getInstance(this).clearDB();
                    Preferences.getInstance(this).clearPrefs();
                    startActivity(new Intent(MainActivity.this,GuideActivity.class));
                    finish();
                }
                break;
            case R.id.btn_info_confirm:
                joinTourGuideGroup(guideId,personInfoPopup.getInputName(),personInfoPopup.getInputPhone());
                personInfoPopup.dismiss();
                break;
            case R.id.floating_btn_call:
                MobclickAgent.onEvent(this, UmengEvent.home_call_guide_btn_click);
                String tmp = Preferences.getInstance(this).getTourGuidePhone();
                Uri uri=Uri.parse("tel:"+tmp);
                Intent callIntent=new Intent();
                callIntent.setAction(Intent.ACTION_CALL);
                callIntent.setData(uri);
                startActivity(callIntent);
                break;
        }
    }

    private void joinTourGuideGroup(String guideId,String realName,String phone){
        if(phone==null||phone.length()!=11){
            return;
        }
        Preferences.getInstance(this).setUserPhone(phone);
        if(TextUtils.isEmpty(realName)){
            realName = Preferences.getInstance(this).getNickName();
        }else{
            Preferences.getInstance(this).setUserName(realName);
        }
        Intent intent = new Intent(this, GroupService.class);
        if (!isBound) {
            serviceConnection = new GroupServiceConnection(this);
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
            isBound = true;
        }
        Bundle bundle = new Bundle();
        bundle.putInt("command", GroupService.GroupCommand.COMMAND_JOIN_GUIDE_GROUP);
        bundle.putString("admin_id", guideId);
        bundle.putString("name", realName);
        bundle.putString("phone",phone);
        intent.putExtras(bundle);
        startService(intent);
        Toast.makeText(this, R.string.group_join_tip, Toast.LENGTH_SHORT).show();
    }


    private IndicatorViewPager.IndicatorPagerAdapter adapter = new IndicatorViewPager
            .IndicatorFragmentPagerAdapter(getSupportFragmentManager()) {

        @Override
        public View getViewForTab(int position, View convertView, ViewGroup container) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tab_item, container, false);
            }
            TextView textView = (TextView) convertView;
            textView.setText(position == 0 ? R.string.tab_text_photo : R.string.tab_text_message);
            textView.setAlpha(position == 0 ? 1.0f : 0.7f);
            textView.setPadding(DeviceUtils.dip2px(MainActivity.this,16),0, DeviceUtils.dip2px(MainActivity.this,16),0);
            return convertView;
        }

        @Override
        public Fragment getFragmentForPage(int position) {

            return position == 0 ? new TabRecentPhotoFragment() : new TabMessageFragment();
        }

        @Override
        public int getCount() {
            return 2;
        }
    };

    @Override
    public void onIndicatorPageChange(int preItem, int currentItem) {
        try{
            TextView preHeadText = (TextView)indicator.getItemView(preItem);
            TextView curHeadText = (TextView)indicator.getItemView(currentItem);
            preHeadText.setAlpha(0.7f);
            curHeadText.setAlpha(1.0f);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (data == null || data.getStringExtra("info") == null) {
                Toast.makeText(this,R.string.scan_qr_wrong,Toast.LENGTH_SHORT).show();
                return;
            }

            String urlInfo = data.getStringExtra("info");

            if(!urlInfo.contains("pai.ai")){
                Toast.makeText(this,R.string.scan_qr_wrong,Toast.LENGTH_SHORT).show();
                return;
            }
            LogHelper.d("czy","qr scan result = "+urlInfo);
            boolean isFromGuideApp = urlInfo.contains("tgu");
            if(isFromGuideApp){
                MobclickAgent.onEvent(this, UmengEvent.home_scan_tour_back);
                guideId = urlInfo.substring(urlInfo.lastIndexOf("/") + 1);
                if(!TextUtils.isEmpty(Preferences.getInstance(this).getUserPhone())){
                    joinTourGuideGroup(guideId,Preferences.getInstance(this).getUserName(),Preferences.getInstance(this).getUserPhone());
                }else{
                    personInfoPopup = new PersonInfoPopup(this,this);
                    personInfoPopup.showPopupWindow();
                }
               return;
            }
            boolean isFromAPP = urlInfo.contains("pai.ai/g/");
            MobclickAgent.onEvent(this, isFromAPP? UmengEvent.home_scan_group_back:UmengEvent.home_scan_session_back);
            String groupId = urlInfo.substring(urlInfo.lastIndexOf("/") + 1);
            if (requestCode == JOIN_REQUEST_CODE) {
                Intent intent = new Intent(this, GroupService.class);
                if (!isBound) {
                    serviceConnection = new GroupServiceConnection(this);
                    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
                    isBound = true;
                }
                Bundle bundle = new Bundle();
                bundle.putInt("command", GroupService.GroupCommand.COMMAND_JOIN_GROUP);
                bundle.putString("group_id", groupId);
                bundle.putBoolean("isFromAPP", isFromAPP);
                bundle.putString("nickname", Preferences.getInstance(this).getNickName());
                intent.putExtras(bundle);
                startService(intent);
                Toast.makeText(this, R.string.group_join_tip, Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onCommandCommitFail(int command, String msg) {
        if (command == GroupService.GroupCommand.COMMAND_JOIN_GROUP||command == GroupService.GroupCommand.COMMAND_JOIN_GUIDE_GROUP) {
            if(TextUtils.isEmpty(msg)){
                msg = getString(R.string.group_join_fail_tip);
            }
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onCommandCommitSuccess(int command, Object response) {
        if(command == GroupService.GroupCommand.COMMAND_JOIN_GUIDE_GROUP){
            Preferences.getInstance(this).setTourMode(true);
            Intent intent = new Intent(this, MyLocationService.class);
            intent.putExtra("command",MyLocationService.COMMAND_START_LOCATION);
            startService(intent);
        }
        if (command == GroupService.GroupCommand.COMMAND_JOIN_GROUP||command == GroupService.GroupCommand.COMMAND_JOIN_GUIDE_GROUP) {
            GroupInfo info = (GroupInfo) response;
            Intent intent = new Intent(this, GroupActivity.class);
            intent.putExtra("group", info);
            startActivity(intent);
        }
    }

    private static class GroupServiceConnection implements ServiceConnection {

        private GroupService.GroupServiceListener listener;

        public GroupServiceConnection(GroupService.GroupServiceListener listener) {
            this.listener = listener;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            GroupService.MyBinder binder = (GroupService.MyBinder) service;
            binder.getService().registerServiceListener(listener);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

}
