package kr.co.icontrols.iotplatform;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import kr.co.icontrols.iotplatform.DataClass.DeviceGroupInfo;
import kr.co.icontrols.iotplatform.DataClass.DeviceInfo;
import kr.co.icontrols.iotplatform.DataClass.UserInfo;
import kr.co.icontrols.iotplatform.Database.DBUtil;
import kr.co.icontrols.iotplatform.utils.HttpApi;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_DEVICE_HOME;
import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_DEVICE_RANK;
import static kr.co.icontrols.iotplatform.Database.DatabaseHelper.TABLE_SMART_LIGHT;
import static kr.co.icontrols.iotplatform.PopupActivity.POPUP_BUNDLE;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.DismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ErrorLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.ForceDismissConnectDialog;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.WarnLogOutput;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.displayProgress;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getCircleBitmap;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.getGroupImageResource;
import static kr.co.icontrols.iotplatform.utils.CommonUtils.showNotiMsg;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_BEFORE_ACTIVITY;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_DEVICE_ID;
import static kr.co.icontrols.iotplatform.utils.Constants.EXTRA_GROUP_LIST;
import static kr.co.icontrols.iotplatform.utils.Constants.GROUP_LIST_COUNT_LINE;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_ADD_GROUP;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_INPUT_DEVICE_NAME;
import static kr.co.icontrols.iotplatform.utils.Constants.RESULT_UPDATE_DATA;
import static kr.co.icontrols.iotplatform.utils.HttpApi.HTTP_OK;

public class LightRegisterDeviceFinishActivity extends AppCompatActivity implements View.OnClickListener {

    private final String TAG = "LightRegisterDeviceFinish";

    private TextView txtCompletedDeviceName;
    private LinearLayout mLayoutGroups;
    private ArrayList<ImageView> mImgViewList = new ArrayList<>();


    private String mDeviceId, deviceId, deviceType, firmwareVersion, friendlyName, sharedFriendlyName, ownerId, dgroupId, dgroupName;

    private boolean isChangeName, isChangeGroup;

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

        mDeviceId = getIntent().getStringExtra(EXTRA_DEVICE_ID);
        isChangeName = false;
        isChangeGroup = true;

        txtCompletedDeviceName = findViewById(R.id.txtCompletedDeviceName);
        mLayoutGroups = findViewById(R.id.layoutGroups);

        //UserInfo, Device 재갱신을 위한 Device list 초기화
        UserInfo.updateTimeUserInfo = 0;
        UserInfo.updateTimeDevice = 0;
        UserInfo.devices.clear();

        getDetailDeviceInfo(mDeviceId);
    }

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

    @Override
    protected void onPause() {
        ForceDismissConnectDialog();
        super.onPause();
    }

    @Override
    public void onBackPressed() {
        //super.onBackPressed();
        actvityExit();
    }

    @Override
    protected void onDestroy() {

        if(mImgViewList != null) {
            mImgViewList.clear();
        }

        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        /*
        final View fv = v;
        fv.setEnabled(false);
        Timer buttonTimer = new Timer();
        buttonTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            fv.setEnabled(true);
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {

                        }
                    }
                });
            }
        }, 500);
        */

        switch (v.getId()) {
            case R.id.btnBack:
                onBackPressed();
                break;
            case R.id.btnCompleted:
                actvityExit();
                break;
            case R.id.btnEditDeviceName:{
                Intent intent = new Intent(this, PopupActivity.class);
                intent.putExtra(PopupActivity.POPUP_MODE, PopupActivity.MODE_INPUT);
                Bundle b = new Bundle();
                if (txtCompletedDeviceName.getText().toString().isEmpty()) {
                    b.putString(PopupActivity.POPUP_INPUT, "");
                } else {
                    b.putString(PopupActivity.POPUP_INPUT, txtCompletedDeviceName.getText().toString());
                }
                intent.putExtra(POPUP_BUNDLE, b);
                intent.putExtra(PopupActivity.POPUP_TITLE_TEXT, getString(R.string.change_device_name));
                startActivityForResult(intent, RESULT_INPUT_DEVICE_NAME);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_INPUT_DEVICE_NAME:
                if (resultCode == RESULT_OK) {
                    Bundle b = data.getBundleExtra(POPUP_BUNDLE);
                    if(b != null) {
                        try {
                            String newValue = b.getString(PopupActivity.POPUP_INPUT);
                            if(!newValue.equals(txtCompletedDeviceName.getText().toString())) {
                                changeDeviceName(mDeviceId, newValue);
                            }
                        } catch (Exception e) {
                            // Log failure
                            showNotiMsg(LightRegisterDeviceFinishActivity.this,getString(R.string.snackbar_fail_change_device_name));
                        }
                    } else {
                        showNotiMsg(LightRegisterDeviceFinishActivity.this,getString(R.string.snackbar_fail_change_device_name));
                    }
                }
                break;

            case RESULT_ADD_GROUP:
                if (resultCode == RESULT_OK) {
                    displayProgress(this,"","");
                    getMyDeviceGroup();
                }
                break;
        }
    }

    private void actvityExit() {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    public void getDetailDeviceInfo(String device_Id){
        displayProgress(this,"","");
        try {
            HttpApi.getDeviceInfo(device_Id, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(onFailure)\n" + e.toString());
                    DismissConnectDialog();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code() == HTTP_OK) {
                        WarnLogOutput(TAG, "HttpApi.getDeviceInfo(onResponse) : HTTP_OK");
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());

                            deviceId = json_data.isNull("deviceId") ? "" : json_data.getString("deviceId");
                            deviceType = json_data.isNull("deviceType") ? "" : json_data.getString("deviceType");
                            firmwareVersion = json_data.isNull("firmwareVersion") ? "" : json_data.getString("firmwareVersion");
                            friendlyName = json_data.isNull("friendlyName") ? "" : json_data.getString("friendlyName");
                            sharedFriendlyName = json_data.isNull("sharedFriendlyName") ? "" : json_data.getString("sharedFriendlyName");
                            ownerId = json_data.isNull("ownerId") ? "" : json_data.getString("ownerId");
                            dgroupId = json_data.isNull("dgroupId") ? "" : json_data.getString("dgroupId");
                            dgroupName = json_data.isNull("dgroupName") ? "" : json_data.getString("dgroupName");

                            //UI 업데이트
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    txtCompletedDeviceName.setText(friendlyName);
                                    getMyDeviceGroup();
                                }
                            });

                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(JSONException)\n" + e.toString());
                            DismissConnectDialog();
                        }
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(onResponse) JSONException : " + e.toString());
                        }
                        DismissConnectDialog();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.getDeviceInfo(Exception)\n" + e.toString());
            DismissConnectDialog();
        }
    }

    private void changeDeviceName(final String deviceId, final String name) {
        displayProgress(this,"","");
        try {
            HttpApi.modifyDeviceInfo(deviceId,
                    name,
                    new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(onFailure)\n" + e.toString());
                            showNotiMsg(LightRegisterDeviceFinishActivity.this,getString(R.string.snackbar_fail_change_device_name));
                            DismissConnectDialog();
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            if(response.code() == HttpApi.HTTP_NO_CONTENT) {
                                WarnLogOutput(TAG, "HttpApi.modifyDeviceInfo(onResponse) HTTP_NO_CONTENT");

                                final DeviceInfo itemS = DBUtil.getDeviceInfoForId(TABLE_SMART_LIGHT,deviceId);
                                if(itemS != null) {
                                    itemS.friendlyName = name;
                                    DBUtil.updateDeviceItem(TABLE_SMART_LIGHT,itemS);
                                }

                                final DeviceInfo itemH = DBUtil.getDeviceInfoForId(TABLE_DEVICE_HOME,deviceId);
                                if(itemH != null) {
                                    itemH.friendlyName = name;
                                    DBUtil.updateDeviceItem(TABLE_DEVICE_HOME,itemH);
                                }

                                final DeviceInfo itemR = DBUtil.getDeviceInfoForId(TABLE_DEVICE_RANK,deviceId);
                                if(itemR != null) {
                                    itemR.friendlyName = name;
                                    DBUtil.updateDeviceItem(TABLE_DEVICE_RANK,itemR);
                                }

                                isChangeName = true;
                                friendlyName = name;
                                for(int i = 0 ; i < UserInfo.devices.size() ; i++) {
                                    if(UserInfo.devices.get(i).deviceId.equals(deviceId)) {
                                        if(!UserInfo.devices.get(i).friendlyName.equals(friendlyName)) {
                                            UserInfo.devices.get(i).friendlyName = friendlyName;
                                        }
                                    }
                                }

                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        showNotiMsg(LightRegisterDeviceFinishActivity.this,getString(R.string.snackbar_successed_change_device_name));
                                        txtCompletedDeviceName.setText(friendlyName);
                                        DismissConnectDialog();
                                    }
                                });
                            } else {
                                ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                                showNotiMsg(LightRegisterDeviceFinishActivity.this,getString(R.string.snackbar_fail_change_device_name));
                                DismissConnectDialog();
                                try {
                                    JSONObject json_data = new JSONObject(response.body().string());
                                    ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(onResponse) body : " + json_data.toString());
                                } catch (JSONException e) {
                                    ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(onResponse) JSONException : " + e.toString());
                                }
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.modifyDeviceInfo(Exception)\n" + e.toString());
            showNotiMsg(LightRegisterDeviceFinishActivity.this,getString(R.string.snackbar_fail_change_device_name));
            DismissConnectDialog();
        }
    }

    public void getMyDeviceGroup(){
        UserInfo.getGroup(this, new UserInfo.CallbackForUpdate() {
            @Override
            public void updateData() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(UserInfo.dgroups.size() == 0) {
                            ErrorLogOutput(TAG, "mGroupList size : " + UserInfo.dgroups.size());
                        } else {
                            shwoGroupList();
                        }
                        DismissConnectDialog();
                    }
                });
            }
        });

        /*
        UserInfo.dgroups.clear();
        try {
            HttpApi.getDeviceGroupList(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(onFailure)\n" + e.toString());
                    DismissConnectDialog();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if(response.code() == HTTP_OK) {
                        WarnLogOutput(TAG, "HttpApi.getDeviceGroupList(onResponse) : HTTP_OK");
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            JSONArray jarrayAll = new JSONArray(json_data.getString("results"));
                            for (int i = 0; i < jarrayAll.length(); i++) {
                                JSONObject jObject = jarrayAll.getJSONObject(i);
                                DeviceGroupInfo item = new DeviceGroupInfo(jObject.isNull("dgroupId") ? "" : jObject.getString("dgroupId"),
                                        jObject.isNull("friendlyName") ? "" : jObject.getString("friendlyName"),
                                        jObject.isNull("icon") ? "" : jObject.getString("icon"),
                                        jObject.isNull("index") ? 99 : jObject.getInt("index"));

                                UserInfo.dgroups.add(item);
                            }

                            //UI 업데이트
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(UserInfo.dgroups.size() == 0) {
                                        ErrorLogOutput(TAG, "mGroupList size : " + UserInfo.dgroups.size());
                                    } else {
                                        shwoGroupList();
                                    }
                                    DismissConnectDialog();
                                }
                            });
                        } catch (JSONException e) {
                            e.printStackTrace();
                            ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(JSONException)\n" + e.toString());
                            DismissConnectDialog();
                        }
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(onResponse) JSONException : " + e.toString());
                        }
                        DismissConnectDialog();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.getDeviceGroupList(Exception)\n" + e.toString());
            DismissConnectDialog();
        }
        */
    }


    private void changeGroup(final String dgroupId, final String groupFriendlyName, final String deviceId, final int index) {
        displayProgress(this,"","");
        try {
            HttpApi.connectDeviceInDeviceGroup(dgroupId, deviceId, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                    ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onFailure)\n" + e.toString());
                    showNotiMsg(LightRegisterDeviceFinishActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
                    DismissConnectDialog();
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.code() == HttpApi.HTTP_NO_CONTENT) {
                        WarnLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) HTTP_NO_CONTENT");

                        final DeviceInfo itemS = DBUtil.getDeviceInfoForId(TABLE_SMART_LIGHT,deviceId);
                        if(itemS != null) {
                            itemS.dgroupId = dgroupId;
                            itemS.dgroupName = groupFriendlyName;
                            DBUtil.updateDeviceItem(TABLE_SMART_LIGHT,itemS);
                        }

                        final DeviceInfo itemH = DBUtil.getDeviceInfoForId(TABLE_DEVICE_HOME,deviceId);
                        if(itemH != null) {
                            itemH.dgroupId = dgroupId;
                            itemH.dgroupName = groupFriendlyName;
                            DBUtil.updateDeviceItem(TABLE_DEVICE_HOME,itemH);
                        }

                        final DeviceInfo itemR = DBUtil.getDeviceInfoForId(TABLE_DEVICE_RANK,deviceId);
                        if(itemR != null) {
                            itemR.dgroupId = dgroupId;
                            itemR.dgroupName = groupFriendlyName;
                            DBUtil.updateDeviceItem(TABLE_DEVICE_RANK,itemR);
                        }

                        for(int i = 0; i < UserInfo.devices.size() ; i++) {
                            if(UserInfo.devices.get(i).deviceId.equals(deviceId)) {
                                UserInfo.devices.get(i).dgroupName = friendlyName;
                                UserInfo.devices.get(i).dgroupId = groupFriendlyName;
                            }
                        }

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for(int i = 0; i < mImgViewList.size() ; i++) {
                                    mImgViewList.get(i).setImageBitmap(getCircleBitmap(getGroupImageResource(UserInfo.dgroups.get(i).icon),i==index));
                                }
                                showNotiMsg(LightRegisterDeviceFinishActivity.this, "그룹을 변경하였습니다.");
                                DismissConnectDialog();
                            }
                        });
                    } else {
                        ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) Error code : " + response.code() + "\nresponse : " + response.toString());
                        showNotiMsg(LightRegisterDeviceFinishActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
                        try {
                            JSONObject json_data = new JSONObject(response.body().string());
                            ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) body : " + json_data.toString());
                        } catch (JSONException e) {
                            ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(onResponse) JSONException : " + e.toString());
                        }
                    }
                    DismissConnectDialog();
                }
            });
        }  catch (Exception e) {
            e.printStackTrace();
            ErrorLogOutput(TAG, "HttpApi.connectDeviceInDeviceGroup(Exception)\n" + e.toString());
            showNotiMsg(LightRegisterDeviceFinishActivity.this, "그룹 이동 중 오류가 발생하였습니다.");
            DismissConnectDialog();
        }
    }
    private void shwoGroupList() {
        mImgViewList.clear();
        mLayoutGroups.removeAllViews();
        LinearLayout layoutHorizontal = null;
        int lineCount = 0;
        for(int i = 0; i <= UserInfo.dgroups.size(); i++){
            final int pos = i;
            if(i%GROUP_LIST_COUNT_LINE==0) {
                lineCount = 0;
                layoutHorizontal = new LinearLayout(this);
                LinearLayout.LayoutParams lparam = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                layoutHorizontal.setLayoutParams(lparam);
                layoutHorizontal.setOrientation(LinearLayout.HORIZONTAL);
                mLayoutGroups.addView(layoutHorizontal);

                LinearLayout spacelayout = new LinearLayout(this);
                LinearLayout.LayoutParams slparam = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                slparam.weight = 1;
                spacelayout.setLayoutParams(slparam);
                spacelayout.setOrientation(LinearLayout.HORIZONTAL);
                layoutHorizontal.addView(spacelayout);
            }

            if(layoutHorizontal != null) {
                lineCount++;
                final View child = getLayoutInflater().inflate(R.layout.listview_horizontal_group_item, null);
                final TextView txtGroupName = child.findViewById(R.id.txtGroup);
                final ImageView imgGroup = child.findViewById(R.id.imgGroup);
                if(pos < UserInfo.dgroups.size()) {
                    mImgViewList.add(imgGroup);
                    txtGroupName.setText(UserInfo.dgroups.get(pos).friendlyName);
                    imgGroup.setImageBitmap(getCircleBitmap(getGroupImageResource(UserInfo.dgroups.get(pos).icon), pos == 0));
                } else {
                    txtGroupName.setText("추가하기");
                    imgGroup.setScaleType(ImageView.ScaleType.CENTER);
                    imgGroup.setImageResource(R.drawable.ico_add);
                    imgGroup.setBackgroundResource(R.drawable.background_circle_add_device_icon);
                }
                layoutHorizontal.addView(child);

                LinearLayout spacelayout = new LinearLayout(this);
                LinearLayout.LayoutParams slparam = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                slparam.weight = 1;
                spacelayout.setLayoutParams(slparam);
                spacelayout.setOrientation(LinearLayout.HORIZONTAL);
                layoutHorizontal.addView(spacelayout);

                //Click Event
                if(pos < UserInfo.dgroups.size()) {
                    child.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            changeGroup(UserInfo.dgroups.get(pos).dgroupId, UserInfo.dgroups.get(pos).friendlyName, mDeviceId, pos);
                        }
                    });
                } else {
                    child.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(LightRegisterDeviceFinishActivity.this, AddGroupActivity.class);
                            intent.putExtra(EXTRA_GROUP_LIST, UserInfo.dgroups);
                            intent.putExtra(EXTRA_BEFORE_ACTIVITY,"LightRegisterDeviceFinishActivity");
                            startActivityForResult(intent,RESULT_ADD_GROUP);
                        }
                    });
                }
            }

            if(i == UserInfo.dgroups.size() && lineCount < GROUP_LIST_COUNT_LINE) {
                while(lineCount < GROUP_LIST_COUNT_LINE) {
                    lineCount++;
                    final View child = getLayoutInflater().inflate(R.layout.listview_horizontal_group_item, null);
                    final TextView txtGroupName = child.findViewById(R.id.txtGroup);
                    final ImageView imgGroup = child.findViewById(R.id.imgGroup);
                    txtGroupName.setVisibility(View.INVISIBLE);
                    imgGroup.setVisibility(View.INVISIBLE);
                    layoutHorizontal.addView(child);

                    LinearLayout spacelayout = new LinearLayout(this);
                    LinearLayout.LayoutParams slparam = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                    slparam.weight = 1;
                    spacelayout.setLayoutParams(slparam);
                    spacelayout.setOrientation(LinearLayout.HORIZONTAL);
                    layoutHorizontal.addView(spacelayout);
                }
            }
        }
    }
}