package kr.co.hanwha.hifive.admin.admin;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;

import kr.co.hanwha.hifive.HFApplication;
import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.admin.admin.data.AdminPlatformType;
import kr.co.hanwha.hifive.admin.network.AdminNetworkUtil;
import kr.co.hanwha.hifive.base.BaseActivity;
import kr.co.hanwha.hifive.data.model.BaseData;
import kr.co.hanwha.hifive.data.model.SpinnerData;
import kr.co.hanwha.hifive.data.source.MemberDataRepository;
import kr.co.hanwha.hifive.dialog.HFSingleDialog;
import kr.co.hanwha.hifive.enums.BaseAnimationType;
import kr.co.hanwha.hifive.enums.BaseToolbarType;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkCallback;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkError;
import kr.co.hanwha.hifive.util.HFDateUtil;

public class AdminVersionAddActivity extends BaseActivity {
    private Spinner mSpinnerPlatform;
    private EditText mEditTextVersion1;
    private EditText mEditTextVersion2;
    private EditText mEditTextVersion3;
    private ImageButton mImageButtonForced;
    private LinearLayout mLayoutReleased;
    private TextView mTextViewReleased;
    private EditText mEditTextUpdate;
    private EditText mEditTextUrl;
    private EditText mEditTextStringBundle;

    private PlatformSpinnerAdapter mAdapter;

    private ArrayList<SpinnerData> mListSpinner;
    private int mPlatformCode = 0;
    private String mReleaseDate = "";
    private boolean mIsEdit = false;
    private int mId = 0;

    @Override
    protected int getContentViewResource() {
        return R.layout.activity_admin_version_add;
    }

    @Override
    protected BaseToolbarType isToolbarStyle() {
        return BaseToolbarType.NONE;
    }

    @Override
    protected BaseAnimationType isShowActivityAnimation() {
        return BaseAnimationType.RIGHT;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mSpinnerPlatform = (Spinner) findViewById(R.id.platform_spinner);
        mEditTextVersion1 = (EditText) findViewById(R.id.version1_editText);
        mEditTextVersion2 = (EditText) findViewById(R.id.version2_editText);
        mEditTextVersion3 = (EditText) findViewById(R.id.version3_editText);
        mImageButtonForced = (ImageButton) findViewById(R.id.forced_imageButton);
        mLayoutReleased = (LinearLayout) findViewById(R.id.released_linearLayout);
        mTextViewReleased = (TextView) findViewById(R.id.released_textView);
        mEditTextUpdate = (EditText) findViewById(R.id.update_editText);
        mEditTextUrl = (EditText) findViewById(R.id.url_editText);
        mEditTextStringBundle = (EditText) findViewById(R.id.stringBundle_editText);

        mAdapter = new PlatformSpinnerAdapter(this);
        mSpinnerPlatform.setAdapter(mAdapter);
        mSpinnerPlatform.setOnItemSelectedListener(onItemSelectedListener);

        mEditTextUpdate.setText(getString(R.string.alert_update_message));

        //Initialize spinner data
        mListSpinner = new ArrayList<>();
        mListSpinner.add(new SpinnerData("iPhone", 100));
        mListSpinner.add(new SpinnerData("Android", 300));
        mAdapter.addItems(mListSpinner);
        mAdapter.notifyDataSetChanged();

        findViewById(R.id.back_imageButton).setOnClickListener(onClickListener);
        findViewById(R.id.save_textView).setOnClickListener(onClickListener);
        mImageButtonForced.setOnClickListener(onClickListener);
        mLayoutReleased.setOnClickListener(onClickListener);

        mIsEdit = getIntent().getBooleanExtra("IS_EDIT", false);
        // Initialize Data
        if (mIsEdit) {
            mId = getIntent().getIntExtra("id", 0);
            mPlatformCode = getIntent().getIntExtra("platform_type", 0);
            String version = getIntent().getStringExtra("version");
            String string_bundle = getIntent().getStringExtra("string_bundle");
            boolean is_forced = getIntent().getBooleanExtra("is_forced", false);
            String update_notice = getIntent().getStringExtra("update_notice");
            String update_url = getIntent().getStringExtra("update_url");
            String releasedAt = getIntent().getStringExtra("released_at");
            mReleaseDate = HFDateUtil.getChangeDateFormat(releasedAt, HFDateUtil.FORMAT_COMMON_SERVER, HFDateUtil.FORMAT_TASK_ADD_DUEDATE_SERVER);

            int index = -1;
            for (int i = 0; i < mListSpinner.size(); i++) {
                if (mPlatformCode == (int) mListSpinner.get(i).getValue()) {
                    index = i;
                    break;
                }
            }
            if (index != -1)
                mSpinnerPlatform.setSelection(index);

            int version1 = 0;
            int version2 = 0;
            int version3 = 0;
            try {
                String versions[] = version.split("\\.");
                if (versions.length == 3) {
                    version1 = Integer.parseInt(versions[0]);
                    version2 = Integer.parseInt(versions[1]);
                    version3 = Integer.parseInt(versions[2]);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            mEditTextVersion1.setText(Integer.toString(version1));
            mEditTextVersion2.setText(Integer.toString(version2));
            mEditTextVersion3.setText(Integer.toString(version3));

            mImageButtonForced.setSelected(is_forced);

            mEditTextUpdate.setText(TextUtils.isEmpty(update_notice) ? "" : update_notice);

            mEditTextUrl.setText(TextUtils.isEmpty(update_url) ? "" : update_url);

            mEditTextStringBundle.setText(TextUtils.isEmpty(string_bundle) ? "" : string_bundle);

            setReleasedDate(mReleaseDate);
        } else {
            setReleasedDate(HFDateUtil.getDateFormatToday(HFDateUtil.FORMAT_TASK_ADD_DUEDATE_SERVER));
        }
    }

    /**************************************************
     * Support methods
     **************************************************/
    public void setPlatform(SpinnerData data) {
        if (data == null) return;

        mPlatformCode = (int) data.getValue();
        if (mPlatformCode == AdminPlatformType.IPHONE.getCode()) {
            if (HFApplication.SERVER == HFApplication.SERVER_TYPE.REAL)
                mEditTextUrl.setText("https://qtalk.dreamplus.center/downloads/b/quest-ios-current.plist");
            else
                mEditTextUrl.setText("https://qtalk.dreamplus.center/downloads/b/quest-ios-dev.plist");
        } else if (mPlatformCode == AdminPlatformType.ANDROID.getCode()) {
            if (HFApplication.SERVER == HFApplication.SERVER_TYPE.REAL)
                mEditTextUrl.setText("https://qtalk.dreamplus.center/downloads/b/quest-android-current.apk");
            else
                mEditTextUrl.setText("https://qtalk.dreamplus.center/downloads/b/quest-android-dev.apk");
        }
    }

    public void showCalendarDialog() {
        new AdminCalendarDialog(this, mReleaseDate, new AdminCalendarDialog.OnDialogCallback() {
            @Override
            public void onConfirm(@NonNull String selectedDate) {
                setReleasedDate(selectedDate);
            }
        }).show();
    }

    public void setReleasedDate(String selectedDate) {
        mReleaseDate = selectedDate;
        mTextViewReleased.setText(selectedDate);
    }

    public void doSave() {
        String encryption_member_id = MemberDataRepository.getInstance().getEncryptionMemberId();
        String version = mEditTextVersion1.getText().toString() + "." + mEditTextVersion2.getText().toString() + "." + mEditTextVersion3.getText().toString();
        String string_bundle = mEditTextStringBundle.getText().toString();
        boolean is_forced = mImageButtonForced.isSelected();
        String update_notice = mEditTextUpdate.getText().toString();
        String update_url = mEditTextUrl.getText().toString();

        if ("0.0.0".equals(version)) {
            showToast("버전 정보를 입력해주세요");
            return;
        }

        if (TextUtils.isEmpty(update_notice)) {
            showToast("업데이트 내용을 입력해주세요");
            return;
        }

        if (TextUtils.isEmpty(update_url)) {
            showToast("다운로드 경로를 입력해주세요");
            return;
        }


        AdminNetworkUtil networkUtil = new AdminNetworkUtil();
        networkUtil.requestClientVersionAdd(this, encryption_member_id,
                mPlatformCode,
                mReleaseDate,
                version,
                string_bundle,
                is_forced,
                update_notice,
                update_url,
                new HanwhaNetworkCallback<BaseData>() {
                    @Override
                    public void onSuccess(final BaseData response) {
                        showToast("버전 정보가 등록되었습니다.");
                        setResult(RESULT_OK);
                        finish();
                    }

                    @Override
                    public void onFailure(HanwhaNetworkError error) {
                        showAlert(error, new HFSingleDialog.OnDialogCallback() {
                            @Override
                            public void onPositive() {

                            }
                        });
                    }

                    @Override
                    public void onPreExecute() {
                        showLoadingDialog(true);
                    }

                    @Override
                    public void onPostExecute() {
                        showLoadingDialog(false);
                    }
                });
    }

    public void doEdit() {
        String encryption_member_id = MemberDataRepository.getInstance().getEncryptionMemberId();
        String version = mEditTextVersion1.getText().toString() + "." + mEditTextVersion2.getText().toString() + "." + mEditTextVersion3.getText().toString();
        String string_bundle = mEditTextStringBundle.getText().toString();
        boolean is_forced = mImageButtonForced.isSelected();
        String update_notice = mEditTextUpdate.getText().toString();
        String update_url = mEditTextUrl.getText().toString();

        if ("0.0.0".equals(version)) {
            showToast("버전 정보를 입력해주세요");
            return;
        }

        if (TextUtils.isEmpty(update_notice)) {
            showToast("업데이트 내용을 입력해주세요");
            return;
        }

        if (TextUtils.isEmpty(update_url)) {
            showToast("다운로드 경로를 입력해주세요");
            return;
        }


        AdminNetworkUtil networkUtil = new AdminNetworkUtil();
        networkUtil.requestClientVersionUpdate(this, encryption_member_id,
                mId,
                mPlatformCode,
                mReleaseDate,
                version,
                string_bundle,
                is_forced,
                update_notice,
                update_url,
                new HanwhaNetworkCallback<BaseData>() {
                    @Override
                    public void onSuccess(final BaseData response) {
                        showToast("버전 정보가 수정되었습니다.");
                        setResult(RESULT_OK);
                        finish();
                    }

                    @Override
                    public void onFailure(HanwhaNetworkError error) {
                        showAlert(error, new HFSingleDialog.OnDialogCallback() {
                            @Override
                            public void onPositive() {

                            }
                        });
                    }

                    @Override
                    public void onPreExecute() {
                        showLoadingDialog(true);
                    }

                    @Override
                    public void onPostExecute() {
                        showLoadingDialog(false);
                    }
                });
    }

    /**************************************************
     * AdapterView.OnItemSelectedListener
     **************************************************/
    AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if (mAdapter == null) return;

//            int color = HFCommonUtil.getColor(AdminVersionAddActivity.this, (int) mListSpinner.get(position).getValue());
//            setFontColor(color);
            setPlatform(mListSpinner.get(position));
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };

    /**************************************************
     * View.OnClickListener
     **************************************************/
    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.back_imageButton:
                    finish();
                    break;
                case R.id.save_textView:
                    if (mIsEdit)
                        doEdit();
                    else {
                        doSave();
                    }
                    break;
                case R.id.forced_imageButton:
                    mImageButtonForced.setSelected(!mImageButtonForced.isSelected());
                    break;
                case R.id.released_linearLayout:
                    showCalendarDialog();
                    break;
            }
        }
    };

    /**************************************************
     * BaseAdapter
     **************************************************/
    public class PlatformSpinnerAdapter extends BaseAdapter {
        private Context mContext = null;
        private LayoutInflater mInflater = null;
        private ArrayList<SpinnerData> mListData = new ArrayList<>();

        public PlatformSpinnerAdapter(Context context) {
            this.mContext = context;
            this.mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void clear() {
            mListData.clear();
        }

        public void addItem(SpinnerData item) {
            mListData.add(item);
        }

        public void addItems(ArrayList<SpinnerData> list) {
            if (mListData == null) mListData = new ArrayList<>();
            else mListData.clear();

            mListData.addAll(list);
        }

        @Override
        public int getCount() {
            return mListData.size();
        }

        @Override
        public Object getItem(int position) {
            return mListData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getDropDownView(int position, View view, ViewGroup parent) {
            if (view == null || !view.getTag().toString().equals("DROPDOWN")) {
                view = mInflater.inflate(R.layout.item_admin_default_spinner, parent, false);
                view.setTag("DROPDOWN");
            }

            TextView textViewTitle = (TextView) view.findViewById(R.id.title_textView);
            textViewTitle.setText(mListData.get(position).getKey());
//            int color = HFCommonUtil.getColor(mContext, (int) mListData.get(position).getValue());
//            textViewTitle.setTextColor(color);
            return view;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            if (view == null || !view.getTag().toString().equals("NON_DROPDOWN")) {
                view = mInflater.inflate(R.layout.item_admin_title_spinner, parent, false);
                view.setTag("NON_DROPDOWN");
            }
            TextView textViewTitle = (TextView) view.findViewById(R.id.title_textView);
            textViewTitle.setText(mListData.get(position).getKey());
            return view;
        }
    }
}
