package ibase.android.visionselfie;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements IMainActivity {

    private static final String TAG = "MainActivity";
    private static final int REQUEST_CODE = 9001;

    private boolean mHasPermission;
    public String mCameraOrientation = "none"; // Front-facing or back-facing
    public static String CAMERA_POSITION_FRONT;
    public static String CAMERA_POSITION_BACK;
    private String fixed_sticker = "";

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


//        Toast.makeText(getApplicationContext(), data.toString(), Toast.LENGTH_SHORT).show();

        /*if (data == Uri.parse("https://proteusvision.com")) {
            fixed_sticker = "work_place";
            inflateViewStickersFragmemt();
        }*/
        init(fixed_sticker);


//        forActions();

    }

    private void forActions() {
        init(fixed_sticker);
    }

    private void init(String fixed_sticker) {

        if (mHasPermission) {
            if (checkCameraHardware(this)) {
                Log.d(TAG, "init: open camera fragment");
                startCamera();
            } else {
                showSnackBar("You need a camera to use this application", Snackbar.LENGTH_INDEFINITE);
            }

        } else {
//            showPermissionExplanationDialog();
            verifyPermissions();
        }
    }

    private void showPermissionExplanationDialog() {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle("").setMessage("The app would like to access the Storage to save photos.").setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                verifyPermissions();
            }
        }).setCancelable(false).show();
    }

    private void startCamera() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.camera_container, CameraFragment.newInstance(), getString(R.string.fragment_camera2));
        transaction.commit();
    }

    private void verifyPermissions() {
        Log.d(TAG, "verifyPermissions: asking user for permission");
        final String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), permissions[0]) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this.getApplicationContext(), permissions[1]) == PackageManager.PERMISSION_GRANTED) {
            mHasPermission = true;
            init(fixed_sticker);
        } else {
//            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
//            alertDialogBuilder.setTitle("").setMessage("The app would like to access the Storage to save photos.").setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
            ActivityCompat.requestPermissions(MainActivity.this, permissions, REQUEST_CODE);
//                }
//            }).show();

        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_CODE) {
            if (mHasPermission) {
                init(fixed_sticker);
            } else {
                verifyPermissions();
            }
        }
    }

    /**
     * Check if this device has a camera
     */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }


    private void showSnackBar(String text, int length) {
        View view = this.findViewById(android.R.id.content).getRootView();
        Snackbar.make(view, text, length);
    }

    @Override
    public void setCameraFrontFacing() {
        Log.d(TAG, "setCameraFrontFacing: setting camera to front facing");
        mCameraOrientation = CAMERA_POSITION_FRONT;
    }

    @Override
    public void setCameraBackFacing() {
        Log.d(TAG, "setCameraBackFacing: setting camera to back facing");
        mCameraOrientation = CAMERA_POSITION_BACK;
    }

    @Override
    public boolean isCameraFrontFacing() {
        if (mCameraOrientation.equals(CAMERA_POSITION_FRONT)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean isCameraBackFacing() {
        if (mCameraOrientation.equals(CAMERA_POSITION_BACK)) {
            return true;
        }
        return false;
    }

    @Override
    public void setFrontCameraId(String cameraId) {
        CAMERA_POSITION_FRONT = cameraId;
    }

    @Override
    public void setBackCameraId(String cameraId) {
        CAMERA_POSITION_BACK = cameraId;
    }

    @Override
    public String getFrontCameraId() {
        return CAMERA_POSITION_FRONT;
    }

    @Override
    public String getBackCameraId() {
        return CAMERA_POSITION_BACK;
    }

    @Override
    public void hideStatusBar() {

        View decorView = getWindow().getDecorView();
        //Hide the status bar.
        int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }

    @Override
    public void showStatusBar() {

        View decorView = getWindow().getDecorView();

        //show the status bar.
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
        decorView.setSystemUiVisibility(uiOptions);
    }

    @Override
    public void hideStillShotWidgets() {
        CameraFragment cameraFragment = (CameraFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.fragment_camera2));
        if (cameraFragment != null) {
            if (cameraFragment.isVisible()) {
//                cameraFragment.d
                cameraFragment.drawingStarted();
            }
        }

    }

    @Override
    public void showStillShotWidgets() {
        CameraFragment cameraFragment = (CameraFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.fragment_camera2));
        if (cameraFragment != null) {
            if (cameraFragment.isVisible()) {
//                cameraFragment.d
                cameraFragment.drawingStopped();
            }
        }

    }

    @Override
    public void toggleViewStickersFragment() {

        ViewStickersFragment viewStickersFragment = (ViewStickersFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.view_stickers));
        if (viewStickersFragment != null) {
            if (viewStickersFragment.isVisible()) {
                hideViewStickersFragment(viewStickersFragment);
            } else {
                showViewStickersFragment(viewStickersFragment);
            }
        } else {
            inflateViewStickersFragmemt();
        }

    }

    @Override
    public void addSticker(Drawable sticker) {
        Log.d(TAG, "addSticker: ");
        CameraFragment cameraFragment = (CameraFragment) getSupportFragmentManager().findFragmentByTag(getString(R.string.fragment_camera2));
        if (cameraFragment != null) {
            Log.d(TAG, "addSticker: cameraFragment != null ");
            if (cameraFragment.isVisible()) {
                cameraFragment.addSticker(sticker);
            }
        } else {
            Log.d(TAG, "addSticker: cameraFragment == null ");
        }


    }


    private void hideViewStickersFragment(ViewStickersFragment viewStickersFragment) {
        Log.d(TAG, "hideViewStickersFragment: ");
        hideStillShotWidgets();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        transaction.setCustomAnimations(R.anim.slide_in_up, R.anim.slide_in_down, R.anim.slide_out_down, R.anim.slide_out_up);
        transaction.setCustomAnimations(R.anim.slide_down_from_top, R.anim.slide_up_out_of_the_screen);
        transaction.hide(viewStickersFragment);
        transaction.commit();
    }

    private void showViewStickersFragment(ViewStickersFragment viewStickersFragment) {
        Log.d(TAG, "showViewStickersFragment: ");
        showStillShotWidgets();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        transaction.setCustomAnimations(R.anim.slide_in_up, R.anim.slide_in_down, R.anim.slide_out_down, R.anim.slide_out_up);
        transaction.setCustomAnimations(R.anim.slide_down_from_top, R.anim.slide_up_out_of_the_screen);
        transaction.show(viewStickersFragment);
        transaction.commit();
    }

    private void inflateViewStickersFragmemt() {
        Log.d(TAG, "inflateViewStickersFragmemt: ");

        hideStillShotWidgets();

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        transaction.setCustomAnimations(R.anim.slide_in_up, R.anim.slide_in_down, R.anim.slide_out_down, R.anim.slide_out_up);
        transaction.setCustomAnimations(R.anim.slide_down_from_top, R.anim.slide_up_out_of_the_screen);
        transaction.add(R.id.camera_container, ViewStickersFragment.newInstance(), (getString(R.string.view_stickers)));
        transaction.commit();
    }


    @Override
    public void onBackPressed() {

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
        alertDialogBuilder.setTitle("Exit Alert").setMessage("Are you sure want to exit?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
//                super.onBackPressed();
                finish();
            }
        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).show();

    }
}
