package ai.pai.client.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.os.Bundle;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.android.common.utils.DeviceUtils;
import com.android.views.roundrect.RoundedImageView;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;

import ai.pai.client.R;
import ai.pai.client.beans.GroupMemberInfo;
import ai.pai.client.db.DBService;
import ai.pai.client.services.GroupService;
import ai.pai.client.utils.PhotoLoader;
import ai.pai.client.utils.SystemUtils;
import ai.pai.client.utils.UmengEvent;
import ai.pai.client.views.GroupExitPopup;
import ai.pai.client.views.GroupQRPopup;

public class GroupSettingActivity extends BaseActivity implements View.OnClickListener, GroupService.GroupServiceListener {

    private TextView groupNameTextView;
    private TextView groupLockTextView;
    private TextView groupLockHintTextView;
    private TextView groupMemberTextView;
    private ToggleButton groupLockToggleBtn;
    private ImageView modifyNameImg;
    private LinearLayout avatarLayout;
    private String groupId;
    private String groupName;
    private int avatarId;
    private ArrayList<GroupMemberInfo> memberList;

    private boolean isLocked;
    private boolean isAdmin;
    private boolean isBound;
    private GroupService groupService;
    private GroupServiceConnection serviceConnection;

    private GroupExitPopup exitPopup;

    private static final int MODIFY_NAME_REQUEST_CODE = 2100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group_settings);
        SystemUtils.setImmerseLayout(this, findViewById(R.id.title_layout));
        TextView title = (TextView) findViewById(R.id.title_bar_middle_txt);
        title.setText(R.string.group_setting);

        groupId = getIntent().getStringExtra("group_id");
        avatarId = getIntent().getIntExtra("avatar_id", 0);
        groupName = getIntent().getStringExtra("group_name");
        if (TextUtils.isEmpty(groupId)) {
            finish();
            return;
        }
        findViewById(R.id.title_bar_back_layout).setOnClickListener(this);
        findViewById(R.id.title_bar_option_layout).setOnClickListener(this);
        findViewById(R.id.layout_group_qr).setOnClickListener(this);
        findViewById(R.id.layout_group_name).setOnClickListener(this);
        findViewById(R.id.layout_group_member).setOnClickListener(this);
        groupLockTextView = (TextView) findViewById(R.id.tv_group_lock);
        groupNameTextView = (TextView) findViewById(R.id.tv_group_name);
        groupMemberTextView = (TextView) findViewById(R.id.tv_group_member);
        groupLockToggleBtn = (ToggleButton) findViewById(R.id.toggle_group_lock);
        avatarLayout = (LinearLayout) findViewById(R.id.layout_member_avatars);
        modifyNameImg = (ImageView)findViewById(R.id.iv_group_name_modify);
        groupLockHintTextView = (TextView)findViewById(R.id.tv_group_lock_hint);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isBound) {
            serviceConnection = new GroupServiceConnection(this);
            Intent intent = new Intent(this, GroupService.class);
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
            isBound = true;
        }
        fetchGroupInfo();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (groupService != null) {
            groupService.unregisterServiceListener();
        }
        if (isBound) {
            unbindService(serviceConnection);
            isBound = false;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == MODIFY_NAME_REQUEST_CODE) {
            groupNameTextView.setText(data.getStringExtra("group_name"));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_bar_back_layout:
                finish();
                break;
            case R.id.title_bar_option_layout:
                exitPopup = new GroupExitPopup(this, this);
                exitPopup.showPopupWindow();
                break;
            case R.id.tv_pop_exit_group:
                if (!isAdmin) {
                    Intent intent = new Intent(GroupSettingActivity.this, GroupService.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("group_id", groupId);
                    bundle.putInt("command", GroupService.GroupCommand.COMMAND_QUIT_GROUP);
                    intent.putExtras(bundle);
                    startService(intent);
                    finish();
                } else {
                    Toast.makeText(this, R.string.can_not_delete_self, Toast.LENGTH_SHORT).show();
                }
            case R.id.tv_pop_cancel:
                exitPopup.dismiss();
                break;
            case R.id.layout_group_qr:
                MobclickAgent.onEvent(this, UmengEvent.groupconfig_qrcode_layout_click);
                new GroupQRPopup(this, groupId, groupName, avatarId).showPopupWindow();
                break;
            case R.id.layout_group_member:
                Intent memberIntent = new Intent(this, GroupDeleteMemberActivity.class);
                memberIntent.putExtra("group_name", groupName);
                memberIntent.putExtra("group_id", groupId);
                memberIntent.putExtra("isAdmin", isAdmin);
                memberIntent.putExtra("member_list", memberList);
                startActivityForResult(memberIntent, 10);
                break;
            case R.id.layout_group_name:
                if (isAdmin) {
                    Intent intent = new Intent(this, GroupRenameActivity.class);
                    intent.putExtra("group_name", groupName);
                    intent.putExtra("group_id", groupId);
                    startActivityForResult(intent, MODIFY_NAME_REQUEST_CODE);
                }
                break;
        }
    }

    @Override
    public void onCommandCommitFail(int command, String msg) {
        switch (command) {
            case GroupService.GroupCommand.COMMAND_FETCH_GROUP_INFO:
                Toast.makeText(getApplicationContext(), R.string.group_detail_fetch_fail, Toast.LENGTH_SHORT).show();
                break;
            case GroupService.GroupCommand.COMMAND_LOCK_GROUP:
                Toast.makeText(getApplicationContext(), R.string.group_lock_fail, Toast.LENGTH_SHORT).show();
                break;
            case GroupService.GroupCommand.COMMAND_UNLOCK_GROUP:
                Toast.makeText(getApplicationContext(), R.string.group_unlock_fail, Toast.LENGTH_SHORT).show();
                break;
            case GroupService.GroupCommand.COMMAND_QUIT_GROUP:
                Toast.makeText(getApplicationContext(), R.string.quit_group_fail, Toast.LENGTH_SHORT).show();
                break;
        }
    }

    @Override
    public void onCommandCommitSuccess(int command, Object response) {
        switch (command) {
            case GroupService.GroupCommand.COMMAND_FETCH_GROUP_INFO:
                Bundle bundle = (Bundle) response;
                groupName = bundle.getString("groupName");
                isLocked = bundle.getBoolean("isLocked");
                isAdmin = bundle.getBoolean("isAdmin");
                memberList = (ArrayList<GroupMemberInfo>) bundle.getSerializable("memberList");
                groupNameTextView.setText(groupName);
                groupMemberTextView.setText(getString(R.string.member_number,String.valueOf(memberList.size())));
                avatarLayout.removeAllViews();
                int k = 0;
                for (GroupMemberInfo memberInfo : memberList) {
                    RoundedImageView img = new RoundedImageView(this);
                    img.setBorderWidth((float)DeviceUtils.dip2px(this, 1));
                    img.setBorderColor(Color.parseColor("#F7F7F7"));
                    img.setCornerRadius(DeviceUtils.dip2px(this, 5));
                    PhotoLoader.getInstance(this).displayImage(memberInfo.avatarUrl, img,PhotoLoader.getUserAvatarOptions());
                    avatarLayout.addView(img);
                    ViewGroup.LayoutParams params = img.getLayoutParams();
                    params.width = DeviceUtils.dip2px(this, 52);
                    params.height = DeviceUtils.dip2px(this, 52);
                    img.setLayoutParams(params);
                    img.setPadding(6, 6, 6, 6);
                }
                groupLockTextView.setText(isLocked ? R.string.group_is_locked : R.string.group_is_unlocked);
                groupLockHintTextView.setText(isLocked ? R.string.group_locked_hint : R.string.group_unlocked_hint);
                if (isAdmin) {
                    modifyNameImg.setVisibility(View.VISIBLE);
                    groupLockToggleBtn.setVisibility(View.VISIBLE);
                    groupLockToggleBtn.setChecked(isLocked);
                    groupLockToggleBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            Intent intent = new Intent(GroupSettingActivity.this, GroupService.class);
                            Bundle bundle = new Bundle();
                            bundle.putString("group_id", groupId);
                            bundle.putInt("command", isLocked ? GroupService.GroupCommand.COMMAND_UNLOCK_GROUP :
                                    GroupService.GroupCommand.COMMAND_LOCK_GROUP);
                            intent.putExtras(bundle);
                            startService(intent);
                            if(groupService!=null){
                                groupService.registerServiceListener(GroupSettingActivity.this);
                            }
                        }
                    });
                }
                break;
            case GroupService.GroupCommand.COMMAND_LOCK_GROUP:
                isLocked = true;
                groupLockToggleBtn.setChecked(true);
                groupLockTextView.setText(isLocked ? R.string.group_is_locked : R.string.group_is_unlocked);
                groupLockHintTextView.setText(isLocked ? R.string.group_locked_hint : R.string.group_unlocked_hint);
                Toast.makeText(getApplicationContext(), R.string.group_is_locked, Toast.LENGTH_SHORT).show();
                break;
            case GroupService.GroupCommand.COMMAND_UNLOCK_GROUP:
                isLocked = false;
                groupLockToggleBtn.setChecked(false);
                groupLockTextView.setText(isLocked ? R.string.group_is_locked : R.string.group_is_unlocked);
                groupLockHintTextView.setText(isLocked ? R.string.group_locked_hint : R.string.group_unlocked_hint);
                Toast.makeText(getApplicationContext(), R.string.group_is_unlocked, Toast.LENGTH_SHORT).show();
                break;
            case GroupService.GroupCommand.COMMAND_QUIT_GROUP:
                Toast.makeText(getApplicationContext(), R.string.quit_group_success, Toast.LENGTH_SHORT).show();
                DBService.getInstance(getApplicationContext()).deleteGroupByGroupId(groupId);
                break;
        }
    }

    private void fetchGroupInfo() {
        Intent intent = new Intent(this, GroupService.class);
        Bundle bundle = new Bundle();
        bundle.putInt("command", GroupService.GroupCommand.COMMAND_FETCH_GROUP_INFO);
        bundle.putString("group_id", groupId);
        intent.putExtras(bundle);
        startService(intent);
    }

    private 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;
            groupService = binder.getService();
            groupService.registerServiceListener(listener);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}
