package com.yidianling.uikit.business.team.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.yidianling.im.R;
import com.yidianling.uikit.custom.widget.TitleBarBottom;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.ResponseCode;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.constant.TeamFieldEnum;
import com.yidianling.nimbase.common.ToastHelper;
import com.yidianling.nimbase.common.activity.UI;
import com.yidianling.nimbase.common.util.string.StringTextWatcher;

/**
 * 群属性
 * Created by hzxuwen on 2015/4/10.
 */
public class TeamPropertySettingActivity extends UI {

    private static final String EXTRA_TID = "EXTRA_TID";
    public static final String EXTRA_DATA = "EXTRA_DATA";
    private static final String EXTRA_FIELD = "EXTRA_FIELD";

    // view
    private EditText editText;

    // data
    private String teamId;
    private TeamFieldEnum filed;
    private String initialValue;
    private TitleBarBottom mToolbarView;

    /**
     * 修改群某一个属性公用界面
     *
     * @param activity
     * @param teamId
     * @param field
     * @param initialValue
     * @param requestCode
     */
    public static void start(Activity activity, String teamId, TeamFieldEnum field, String initialValue, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(activity, TeamPropertySettingActivity.class);
        intent.putExtra(EXTRA_TID, teamId);
        intent.putExtra(EXTRA_DATA, initialValue);
        intent.putExtra(EXTRA_FIELD, field);
        activity.startActivityForResult(intent, requestCode);
    }

    /**
     * 修改群某一个属性公用界面
     *
     * @param context
     * @param teamId
     * @param field
     * @param initialValue
     */
    public static void start(Context context, String teamId, TeamFieldEnum field, String initialValue) {
        Intent intent = new Intent();
        intent.setClass(context, TeamPropertySettingActivity.class);
        intent.putExtra(EXTRA_TID, teamId);
        intent.putExtra(EXTRA_DATA, initialValue);
        intent.putExtra(EXTRA_FIELD, field);
        context.startActivity(intent);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.im_nim_team_name_activity);

//        ToolBarOptions options = new YDLToolBarOptions();
//        setToolBar(R.id.toolbar, options);
        initToolbar();
        findViews();
        parseIntent();

//        TextView toolbarView = findView(R.id.action_bar_right_clickable_textview);
//        toolbarView.setText(R.string.im_save);
//        toolbarView.setOnClickListener(this);


    }

    private void initToolbar() {
        mToolbarView = findView(R.id.chat_tb);

        mToolbarView.setmRightText(getResources().getString(R.string.im_save));
        mToolbarView.setRightTextColor(getResources().getColor(R.color.platform_main_theme));
        mToolbarView.setOnRightTextClick(new TitleBarBottom.OnTitleBarTextClick() {
            @Override
            public void onClick(View view, boolean isActive) {
                showKeyboard(false);
                complete();
            }
        });

    }

    @Override
    public void setTitle(int titleId) {
        mToolbarView.setTitle(getResources().getString(titleId));
    }

    private void parseIntent() {
        teamId = getIntent().getStringExtra(EXTRA_TID);
        filed = (TeamFieldEnum) getIntent().getSerializableExtra(EXTRA_FIELD);
        initialValue = getIntent().getStringExtra(EXTRA_DATA);

        initData();
    }

    private void initData() {
        int limit = 0;
        switch (filed) {
            case Name:
                setTitle(R.string.im_team_settings_name);
                editText.setHint(R.string.im_team_settings_set_name);
                limit = 64;
                break;
            case Introduce:
                setTitle(R.string.im_team_introduce);
                editText.setHint(R.string.im_team_introduce_hint);
                limit = 512;
                break;
            case Extension:
                setTitle(R.string.im_team_extension);
                editText.setHint(R.string.im_team_extension_hint);
                limit = 65535;
                break;
        }

        if (!TextUtils.isEmpty(initialValue)) {
            editText.setText(initialValue);
            editText.setSelection(initialValue.length());
        }
        editText.addTextChangedListener(new StringTextWatcher(limit, editText));
    }

    private void findViews() {
        editText = (EditText) findViewById(R.id.discussion_name);
        editText.setOnKeyListener(new View.OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                return keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP;
            }

        });
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    complete();
                    return true;
                } else {
                    return false;
                }
            }
        });
        showKeyboardDelayed(editText);

        LinearLayout backgroundLayout = (LinearLayout) findViewById(R.id.background);
        backgroundLayout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showKeyboard(false);
            }
        });
    }

    /**
     * 点击保存
     */
    private void complete() {
        if (filed == TeamFieldEnum.Name) {
            if (TextUtils.isEmpty(editText.getText().toString())) {
                ToastHelper.showToast(this, R.string.im_not_allow_empty);
            } else {
                char[] s = editText.getText().toString().toCharArray();
                int i;
                for (i = 0; i < s.length; i++) {
                    if (String.valueOf(s[i]).equals(" ")) {
                        ToastHelper.showToast(this, R.string.im_now_allow_space);
                        break;
                    }
                }
                if (i == s.length) {
                    saveTeamProperty();
                }
            }
        } else {
            if (TextUtils.equals(editText.getText().toString(), initialValue)) {
                showKeyboard(false);
                finish();
            } else if (TextUtils.isEmpty(teamId)) {
                saved();
            } else {
                saveTeamProperty();
            }
        }
    }

    private void saved() {
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DATA, editText.getText().toString());
        setResult(Activity.RESULT_OK, intent);
        showKeyboard(false);
        finish();
    }

    /**
     * 保存设置
     */
    private void saveTeamProperty() {
        if (teamId == null) { // 讨论组创建时，设置群名称
            Intent intent = new Intent();
            intent.putExtra(EXTRA_DATA, editText.getText().toString());
            setResult(Activity.RESULT_OK, intent);
            finish();
        } else {
            NIMClient.getService(TeamService.class).updateTeam(teamId, filed, editText.getText().toString()).setCallback(new RequestCallback<Void>() {
                @Override
                public void onSuccess(Void param) {
                    ToastHelper.showToast(TeamPropertySettingActivity.this, R.string.im_update_success);
                    saved();
                }

                @Override
                public void onFailed(int code) {
                    if (code == ResponseCode.RES_TEAM_ENACCESS) {
                        ToastHelper.showToast(TeamPropertySettingActivity.this, R.string.im_no_permission);

                    } else {
                        ToastHelper.showToast(TeamPropertySettingActivity.this, String.format(getString(R.string.im_update_failed), code));
                    }
                }

                @Override
                public void onException(Throwable exception) {
                }
            });
        }
    }

    @Override
    public void onBackPressed() {
        showKeyboard(false);
        super.onBackPressed();
    }
}
