package com.cygnusa.hyperm.fragments;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.text.InputType;
import android.util.LayoutDirection;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.LoginActivity;
import com.cygnusa.hyperm.ProductFeedbackFormActivity;
import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.HyperMEnquiryForm;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.CommonMethods;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.Listner360;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.RotateAnimationClass;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GetAllThreeSixtyResponseModel;
import com.cygnusa.hyperm.wrappers.ThreeSixtyHotspotList;
import com.cygnusa.hyperm.wrappers.ThreeSixtyImageDataList;
import com.cygnusa.hyperm.wrappers.ThreeSixtyImageList;
import com.warkiz.widget.IndicatorSeekBar;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import io.github.douglasjunior.androidSimpleTooltip.ArrowDrawable;
import io.github.douglasjunior.androidSimpleTooltip.SimpleTooltip;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.cygnusa.hyperm.MainActivity.img_broucher;
import static com.cygnusa.hyperm.MainActivity.img_rating;
import static com.cygnusa.hyperm.MainActivity.layout1;
import static com.cygnusa.hyperm.util.RotateAnimationClass.animationPosition;
import static com.cygnusa.hyperm.util.RotateAnimationClass.displayImageSB;

public class Hotspot360 extends Fragment implements Listner360, View.OnClickListener {
    double width = 1024.0;
    double height = 660.0;

    ImageView imageView;
    ArrayList<ImageView> views = new ArrayList<>();
    Animation zoomOutAnimation;
    private LinearLayout linearLayoutColor;
    private static final int PERMISSION_REQUEST_CODE = 1;
    int layoutLength = 0, clickablePosition = 0, colorClickPosition = 0;
    ApiService restService;
    ArrayList<ThreeSixtyImageDataList> hotspotArrayList = new ArrayList<>();
    ArrayList<String> imageName = new ArrayList<>();
    private RotateAnimationClass anim;
    private FrameLayout frameLayout;
    private String zipFileURL = "";
    private String checkColorCode = "";
    StorePreference storePreference;
    ProgressBar progressBar;
    private Activity activity;
    private IndicatorSeekBar seekBar;
    private SimpleTooltip popup;
    private ImageView imgNoData, imgLeft, imgRight;
    private LinearLayout lloutWhole;
    int oldPosition = 0;
    ImageView imgBack;
    View rootView;
    List<ThreeSixtyImageList> MODELS = new ArrayList<>();

    @Override
    public void onResume() {
        super.onResume();
        activity = getActivity();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_360, null);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        activity = getActivity();
        imageView = rootView.findViewById(R.id.imageView);
        frameLayout = rootView.findViewById(R.id.hotspot_layout);
        storePreference = new StorePreference(activity);
        progressBar = rootView.findViewById(R.id.progress);
        progressBar.setVisibility(View.GONE);
        TextView txtName = rootView.findViewById(R.id.textView);
        linearLayoutColor = rootView.findViewById(R.id.linear_color);
        imgNoData = rootView.findViewById(R.id.noDataFound);
        imgNoData.setVisibility(View.GONE);
        lloutWhole = rootView.findViewById(R.id.whole_layout);
        imgBack = rootView.findViewById(R.id.logo);
        seekBar = rootView.findViewById(R.id.seekbar);
        restService = ((MainApplication) activity.getApplication()).getClient();
        txtName.setText(storePreference.getStringValue(GlobalData.SELECTED_MODEL_NAME));
        imgLeft = rootView.findViewById(R.id.imgLeft);
        imgRight = rootView.findViewById(R.id.imgRight);
        if (GlobalData.user.getData().getRole().equalsIgnoreCase("16")) {
            seekBar.setVisibility(View.VISIBLE);
            imgRight.setVisibility(View.VISIBLE);
            imgLeft.setVisibility(View.VISIBLE);
        } else {
            seekBar.setVisibility(View.GONE);
            imgRight.setVisibility(View.GONE);
            imgLeft.setVisibility(View.GONE);
        }

        img_broucher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HyperMEnquiryForm.class));
            }
        });
        img_rating.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), ProductFeedbackFormActivity.class));
            }
        });
        layout1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), HyperMEnquiryForm.class));
            }
        });
        imgBack.setOnClickListener(this);
        imgBack.setVisibility(View.INVISIBLE);

        frameLayout.getViewTreeObserver().addOnGlobalLayoutListener(listener);

        return rootView;
    }

    private ViewTreeObserver.OnGlobalLayoutListener listener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            double height = frameLayout.getHeight() / 100.00;
            int newWidth = (int) (height * 155.15);
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) frameLayout.getLayoutParams();
            params.width = newWidth;
            params.height = frameLayout.getHeight();
            params.gravity = Gravity.CENTER;
            params.weight = 0f;
            frameLayout.setLayoutParams(params);
            if (CommonMethods.isNetworkAvailable(Objects.requireNonNull(activity))) {
                if (checkPermission()) {

                    getAllThreeSixtyImages();
                } else {
                    requestPermission();
                }
            } else {
                checkLocal360File();
            }

            frameLayout.getViewTreeObserver().removeOnGlobalLayoutListener(listener);
        }
    };

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = getActivity();
    }

    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(Objects.requireNonNull(activity), android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        return result == PackageManager.PERMISSION_GRANTED;
    }

    private void requestPermission() {
        if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (CommonMethods.isNetworkAvailable(activity)) {
                    getAllThreeSixtyImages();
                } else {
                    CommonMethods.showToast(activity, GlobalData.SERVER_ERROR).show();
                }
            } else {
                Toast.makeText(activity, "Permission Denied", Toast.LENGTH_LONG).show();
            }
        }
    }

    private void checkDownloadableVersion() {
        File dir = new File(Objects.requireNonNull(activity).getExternalFilesDir(null) + File.separator + "hyperm" + storePreference.getStringValue(GlobalData.SELECTED_MODEL) + checkColorCode);
        if (dir.exists()) {
            loadAvailableFiles();
            // setHotspotHighlight(0);
        } else {
            dir.mkdir();
            fileDownloadService(zipFileURL);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void setColorButtons(final List<ThreeSixtyImageList> data) {
        linearLayoutColor.removeAllViews();
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                View view = LayoutInflater.from(activity).inflate(R.layout.personalization_button_layout, null);
                final LinearLayout linearLayout1 = view.findViewById(R.id.lineardrag);
                final TextView imageView = view.findViewById(R.id.txt_round);
                final TextView textView = view.findViewById(R.id.txt_name);
                view.setId(i);
                view.setVisibility(View.INVISIBLE);
                imageView.setId(i);
                textView.setId(i);
                if (colorClickPosition == i)
                    textView.setVisibility(View.VISIBLE);
                else
                    textView.setVisibility(View.GONE);
                ColorStateList csl = new ColorStateList(new int[][]{{}}, new int[]{Color.parseColor(data.get(i).getColor_code())});
                textView.setText(data.get(i).getName());
                imageView.setBackgroundTintList(csl);
                linearLayout1.setId(i);
                linearLayout1.setTag(i + "");
                textView.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
                linearLayout1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        colorClickPosition = linearLayout1.getId();
                        setColorButtons(data);
                        zipFileURL = data.get(colorClickPosition).getZip();
                        checkColorCode = data.get(colorClickPosition).getColor_code();
                        checkDownloadableVersion();
                    }
                });
                linearLayoutColor.addView(view);
            }
        }
    }

    private void getAllThreeSixtyImages() {
        progressBar.setVisibility(View.VISIBLE);
        hotspotArrayList = new ArrayList<>();
        try {
            restService.getAllThreeSixtyImage(storePreference.getStringValue(GlobalData.SELECTED_MODEL)).enqueue(new Callback<GetAllThreeSixtyResponseModel>() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void onResponse(@NonNull Call<GetAllThreeSixtyResponseModel> call, Response<GetAllThreeSixtyResponseModel> response) {
                    // progressBar.setVisibility(View.GONE);
                    SharedPreferences pref = Objects.requireNonNull(getActivity()).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = pref.edit();
                    if (response.body() != null && response.body().getStatus() == 200) {
                        MODELS = response.body().getData();
                        if (MODELS != null && MODELS.size() > 0) {
                            Gson gson = new Gson();
                            JsonElement jsonElement = gson.toJsonTree(
                                    MODELS, new TypeToken<List<ThreeSixtyImageList>>() {
                                    }.getType());
                            editor.putString("360_VIEW_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL),
                                    jsonElement.toString()).apply();
                            if (MODELS.get(clickablePosition).getImagelist() != null && MODELS.get(clickablePosition).getImagelist().size() > 0) {
                                hotspotArrayList.addAll(MODELS.get(clickablePosition).getImagelist());
                                zipFileURL = MODELS.get(clickablePosition).getZip();

                                if (storePreference.getStringValue(GlobalData.OLD_VERSION_CODE) == null || storePreference.getStringValue(GlobalData.OLD_VERSION_CODE).equalsIgnoreCase("")) {
                                    storePreference.setString(GlobalData.OLD_VERSION_CODE, MODELS.get(clickablePosition).getVersion());
                                }
                                layoutLength = MODELS.get(clickablePosition).getImagelist().size();
                                setColorButtons(MODELS);
                                checkColorCode = MODELS.get(clickablePosition).getColor_code();
                                checkDownloadableVersion();
                            } else {
                                checkLocal360File();
                            }

                        } else {

                            checkLocal360File();
                        }
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                        Objects.requireNonNull(getActivity()).finish();
                    } else if (response.body() != null && response.body().getStatus() == 406) {
                        checkLocal360File();
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        //GlobalData.showToast(Objects.requireNonNull(getActivity()), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            startActivity(new Intent(getActivity(), LoginActivity.class));
                            Objects.requireNonNull(getActivity()).finish();
                        }
                        checkLocal360File();
                    } else {
                        checkLocal360File();
                    }

                }

                @Override
                public void onFailure(@NonNull Call<GetAllThreeSixtyResponseModel> call, @NonNull Throwable t) {
                    // progressBar.setVisibility(View.GONE);
                    checkLocal360File();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkLocal360File() {
        SharedPreferences pref = Objects.requireNonNull(getActivity()).getSharedPreferences("PRODUCT_MODULE", Context.MODE_PRIVATE);
        if (pref.getString("360_VIEW_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL), null) != null) {
            Gson gson = new Gson();
            MODELS = gson.fromJson(
                    pref.getString("360_VIEW_" + storePreference.getStringValue(GlobalData.SELECTED_MODEL), null),
                    new TypeToken<List<ThreeSixtyImageList>>() {
                    }.getType());
            if (Objects.requireNonNull(MODELS).get(clickablePosition).getImagelist() != null && MODELS.get(clickablePosition).getImagelist().size() > 0) {
                hotspotArrayList.addAll(MODELS.get(clickablePosition).getImagelist());
                zipFileURL = MODELS.get(clickablePosition).getZip();
                if (storePreference.getStringValue(GlobalData.OLD_VERSION_CODE) == null || storePreference.getStringValue(GlobalData.OLD_VERSION_CODE).equalsIgnoreCase("")) {
                    storePreference.setString(GlobalData.OLD_VERSION_CODE, MODELS.get(clickablePosition).getVersion());
                }
                layoutLength = MODELS.get(clickablePosition).getImagelist().size();
                setColorButtons(MODELS);
                checkColorCode = MODELS.get(clickablePosition).getColor_code();
                checkDownloadableVersion();
            } else {
                lloutWhole.setVisibility(View.GONE);
                seekBar.setVisibility(View.GONE);
                imgNoData.setVisibility(View.VISIBLE);
            }
        } else {
            lloutWhole.setVisibility(View.GONE);
            seekBar.setVisibility(View.GONE);
            imgNoData.setVisibility(View.VISIBLE);
        }
    }

    private void loadAvailableFiles() {
        File file = new File(Objects.requireNonNull(activity).getExternalFilesDir(null) +
                File.separator + "/hyperm" + storePreference.getStringValue(GlobalData.SELECTED_MODEL)
                + checkColorCode);

        imageName = new ArrayList<>();
        if (file.listFiles() != null && file.listFiles().length > 0) {
            for (File f : file.listFiles()) {
                imageName.add(f.getAbsolutePath());
            }
            Collections.sort(imageName, new Comparator<String>() {
                @Override
                public int compare(String lhs, String rhs) {
                    return rhs.compareTo(lhs);
                }
            });
            if (imageName != null && imageName.size() > 0) {
                anim = new RotateAnimationClass(activity, imageName,
                        imageView, false, frameLayout, seekBar, imgLeft, imgRight);
                anim.setPositionChangeListener(Hotspot360.this);
            }
            imgBack.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
        } else {
            if (checkPermission()) {
                fileDownloadService(zipFileURL);
            } else {
                requestPermission();
            }
        }
    }

    private void fileDownloadService(String zip) {

        try {

            restService.downloadFileWithDynamicUrlSync(zip).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        new DownloadDataFromURL(response.body()).execute();
                        progressBar.setVisibility(View.GONE);
                    }

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    progressBar.setVisibility(View.GONE);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void unzip(String zipFile, String location) {
        try {
            ZipInputStream zis = new ZipInputStream(
                    new BufferedInputStream(new FileInputStream(zipFile)));
            try {
                ZipEntry ze;
                int count;
                byte[] buffer = new byte[8192];
                while ((ze = zis.getNextEntry()) != null) {
                    File file = new File(location, ze.getName());
                    File dir = ze.isDirectory() ? file : file.getParentFile();
                    if (!dir.isDirectory() && !dir.mkdirs())
                        throw new FileNotFoundException("Failed to ensure directory: " +
                                dir.getAbsolutePath());
                    if (ze.isDirectory())
                        continue;
                    try (FileOutputStream fout = new FileOutputStream(file)) {
                        while ((count = zis.read(buffer)) != -1)
                            fout.write(buffer, 0, count);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void unzipFiles(String checkColorCode) {
        String hypermDownloadFile = activity.getExternalFilesDir(null) + File.separator + "hyperm" + storePreference.getStringValue(GlobalData.SELECTED_MODEL) + checkColorCode + ".zip";
        File target = new File(activity.getExternalFilesDir(null) + File.separator + "/hyperm" + storePreference.getStringValue(GlobalData.SELECTED_MODEL) + checkColorCode);
        try {
            if (target.mkdir()) {
                System.out.println("Directory created");
            } else {
                System.out.println("Directory is not created");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (target.canWrite()) {
            final File backupDBFolder = new File(target.getPath());
            unzip(hypermDownloadFile, backupDBFolder.getPath());
        }
    }

    private void setHotspotHighlight(final int anim) {
        try {
            for (ImageView view : views) {
                view.clearAnimation();
                frameLayout.removeView(view);
            }
            double w = frameLayout.getWidth() / 100.0;
            double h = frameLayout.getHeight() / 100.0;
            double mwi = getResources().getDimension(R.dimen.textSizeLarge);
            int img_w_h = (int) (frameLayout.getWidth() * (mwi / width));
            views = new ArrayList<>();
            List<ThreeSixtyHotspotList> hotspotLists = hotspotArrayList.get((hotspotArrayList.size() - 1) - anim).getHotspot();
            for (int i = 0; i < hotspotLists.size(); i++) {
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(img_w_h, img_w_h);
                ImageView imageView = new ImageView(activity);
                imageView.setBackgroundColor(Color.TRANSPARENT);
                imageView.setImageResource(R.mipmap.bullet);
                imageView.setId(i);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
                    @Override
                    public void onClick(View v) {
                        if (popup != null)
                            popup.dismiss();
                        popup = new SimpleTooltip.Builder(activity).arrowColor(getResources().getColor(R.color.bg_color))
                                .arrowDirection(ArrowDrawable.AUTO)
                                .anchorView(v)
                                .gravity(Gravity.END)
                                .dismissOnInsideTouch(false)
                                .dismissOnOutsideTouch(false)
                                .maxWidth(R.dimen.layoutsizeExtraLarge)
                                .focusable(true)
                                .contentView(viewPopup(v.getId(), anim), R.id.text_desc)
                                .build();
                        popup.show();
                    }
                });
                double x = 0, y = 0;
                try {
                    if (hotspotLists.get(i).getPointArr() != null) {
                        x = Double.valueOf(hotspotLists.get(i).getPointArr().getX());
                        y = Double.valueOf(hotspotLists.get(i).getPointArr().getY());
                    }
                } catch (NumberFormatException e) {
                    w = 0; // your default value
                }
                double newx = w * ((x / width) * 100.0) - (img_w_h / 2.0);
                double newy = h * ((y / height) * 100.0) - (img_w_h / 2.0);

                params.leftMargin = (int) newx;
                params.topMargin = (int) newy;
                zoomAnimate(imageView);
                frameLayout.addView(imageView, params);
                views.add(imageView);
                imgBack.setVisibility(View.VISIBLE);
                progressBar.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("RtlHardcoded")
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public View viewPopup(int id, int animationPos) {
        View view = LayoutInflater.from(getActivity()).inflate(
                R.layout.popup_window_card, null);
        ImageView imageView = view.findViewById(R.id.popup_image);
        TextView textView1 = view.findViewById(R.id.text_title);
        TextView textViewdesc = view.findViewById(R.id.desc);
        ImageView imgClose = view.findViewById(R.id.img_close_window);
        imgClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popup.dismiss();
            }
        });
        List<ThreeSixtyHotspotList> hotspotLists = hotspotArrayList.get((hotspotArrayList.size() - 1) - animationPos).getHotspot();
        for (int posId = 0; posId < hotspotLists.size(); posId++) {
            if (id == posId) {
                textView1.setText(hotspotLists.get(posId).getTitle());
                textViewdesc.setText(hotspotLists.get(posId).getDescription());
                Glide.with(Objects.requireNonNull(getActivity())).load(hotspotLists.get(posId).getFileUrl()).into(imageView);
                final Configuration configuration = getResources().getConfiguration();
                if (configuration.getLayoutDirection() == LayoutDirection.RTL) {
                    textView1.setGravity(Gravity.RIGHT);
                    textViewdesc.setGravity(Gravity.RIGHT);
                } else {
                    textView1.setGravity(Gravity.LEFT);
                    textViewdesc.setGravity(Gravity.LEFT);
                }
            }
        }
        return view;
    }


    @Override
    public void setHotspot(int animationPosition) {
        if (popup != null)
            popup.dismiss();
        try {
            setHotspotHighlight(animationPosition);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStartAnimation() {

    }

    @Override
    public void onStopAnimation() {
        for (ImageView view : views) {
            view.clearAnimation();
            frameLayout.removeView(view);
        }
        views = new ArrayList<>();
    }


    public void zoomAnimate(View v) {
        zoomOutAnimation = AnimationUtils.loadAnimation(activity, R.anim.zoom_out);
        v.startAnimation(zoomOutAnimation);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        activity = null;
        if (anim != null)
            anim.stopRotationAnimation();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.logo:
                activity.onBackPressed();
                break;
            case R.id.imgLeft:
                int fromRight = animationPosition - 1;
                int toRight = fromRight - 1;
                int k = 1;
                for (int i = fromRight; i >= toRight; i--) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            animationPosition = animationPosition - 1;
                            displayImageSB();
                        }
                    }, k * 30);
                    k++;
                }
                break;
            case R.id.imgRight:
                int from = animationPosition + 1;
                int to = from + 1;
                int j = 1;
                for (int i = from; i <= to; i++) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            animationPosition = animationPosition + 1;
                            displayImageSB();
                        }
                    }, j * 30);
                    j++;
                }
                break;
            default:
        }
    }


    @SuppressLint("StaticFieldLeak")
    private class DownloadDataFromURL extends AsyncTask<String, String, String> {
        ResponseBody body;

        DownloadDataFromURL(ResponseBody body) {
            this.body = body;
        }

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

        @Override
        protected String doInBackground(String... strings) {
            try {
                File hypermDownloadFile = new File(getActivity().getExternalFilesDir(null) + File.separator + "hyperm" + storePreference.getStringValue(GlobalData.SELECTED_MODEL) + checkColorCode + ".zip");
                InputStream inputStream = null;
                OutputStream outputStream = null;
                try {
                    byte[] fileReader = new byte[4096];
                    inputStream = body.byteStream();
                    outputStream = new FileOutputStream(hypermDownloadFile);
                    while (true) {
                        int read = inputStream.read(fileReader);
                        if (read == -1) {
                            break;
                        }
                        outputStream.write(fileReader, 0, read);
                    }
                    outputStream.flush();
                    unzipFiles(checkColorCode);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }

                    if (outputStream != null) {
                        outputStream.close();
                    }
                }

            } catch (IOException ignored) {

            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);

            loadAvailableFiles();
            setHotspotHighlight(0);
            imgBack.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.GONE);
        }
    }

}