package ai.pai.client.fragments;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.common.executors.ThreadExecutor;
import ai.pai.client.utils.HttpPostTask;
import com.android.common.utils.DeviceUtils;
import com.android.common.utils.JSONParseUtils;
import com.android.common.utils.LogHelper;
import com.android.views.progressbar.ProgressWheel;

import org.json.JSONObject;

import java.util.HashMap;

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.qrcode.QRCreateUtils;
import ai.pai.client.utils.UrlContainer;

public class GroupQRFragment extends BaseFragment {

    private ProgressWheel wheel;
    private ImageView groupQRImg;
    private TextView groupJoinHintText;
    private HttpPostTask requestGroupIdTask;
    private int codeWidth;
    private String groupId;
    private String groupName;
    private int defaultAvatarId;


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_group_qr,container,false);
        groupQRImg = (ImageView)rootView.findViewById(R.id.iv_create_group_qrcode);
        groupJoinHintText = (TextView)rootView.findViewById(R.id.tv_create_group_hint);
        wheel = (ProgressWheel)rootView.findViewById(R.id.wheel_wait_http);
        groupName = getArguments().getString("name");
        defaultAvatarId = getArguments().getInt("avatar");
        requestGroupId();
        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(requestGroupIdTask!=null){
            requestGroupIdTask.cancel(true);
        }
    }

    public String getGroupId(){
        return groupId;
    }

    private void requestGroupId(){
        if(!isAdded()){
            return;
        }
        if(requestGroupIdTask!=null && requestGroupIdTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("user_id", Preferences.getInstance(getActivity()).getUserId());
        params.put("group_name",groupName);
        params.put("group_default_avatar",String.valueOf(defaultAvatarId));
        requestGroupIdTask = new HttpPostTask(getActivity(),params) {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                wheel.setVisibility(View.VISIBLE);
                wheel.startSpinning();
            }

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        LogHelper.d(TAG," requestGroupId parseResponse status ok");
                        JSONObject info = json.getJSONObject("data");
                        groupId = JSONParseUtils.getJSONString(info.getString("group_id"));
                        return true;
                    }
                }catch (Exception e){
                    LogHelper.d(TAG," requestGroupId parseResponse error :"+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                wheel.stopSpinning();
                wheel.setVisibility(View.GONE);
                Toast.makeText(getActivity(),R.string.group_create_fail,Toast.LENGTH_LONG).show();
            }

            @Override
            protected void onPostSuccess(Context context) {
                wheel.stopSpinning();
                wheel.setVisibility(View.GONE);

                initQRImageSize();
                super.onPostSuccess(context);

                try{
                    groupQRImg.setImageBitmap(QRCreateUtils.Create2DCode(UrlContainer.QR_APP_GROUP_URL+groupId,codeWidth));
                    groupJoinHintText.setVisibility(View.VISIBLE);
                    groupQRImg.setVisibility(View.VISIBLE);
                    GroupInfo info = new GroupInfo();
                    info.groupAvatarId = defaultAvatarId;
                    info.groupId = groupId;
                    info.groupName = groupName;
                    DBService.getInstance(context).addNewGroup(info);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };
        requestGroupIdTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_CREATE_URL);
    }

    private void initQRImageSize(){
        float scale = DeviceUtils.getScreenWidth(getActivity()) / 720.0f;
        codeWidth = (int) (450 * scale);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) groupQRImg.getLayoutParams();
        params.width = codeWidth;
        params.height = codeWidth;
        groupQRImg.setLayoutParams(params);
    }
}
