package com.b2lmobitech.spottest;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.b2lmobitech.spottest.frags.PreviewFragment;
import com.b2lmobitech.spottest.frags.SingleQuestionFragment;
import com.b2lmobitech.spottest.utils.Utility;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.Date;

public class QuestionsActivity extends AppCompatActivity implements SingleQuestionFragment.Listener {

    private TextView timerText;
    String section,assignId;
    SingleQuestionFragment questionFragment;
    PreviewFragment previewFragment;
    int starttime=0;
    ImageView timerIcon;
    boolean isMock;

    boolean CameraRequest=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_questions);
        timerText=findViewById(R.id.timerText);
        //startTimer(100);
        timerIcon=findViewById(R.id.timerIcon);


        section=getIntent().getStringExtra("section");
        assignId=getIntent().getStringExtra("assignId");
        Log.d("assign",assignId);
        Toolbar toolbar =  findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Bundle bundle=new Bundle();
        bundle.putString("id",section);
        bundle.putString("assignId",assignId);

        isMock=getIntent().getBooleanExtra("mock",false);

        getSupportActionBar().setDisplayShowTitleEnabled(false);

        /*    previewFragment=new PreviewFragment();
            bundle.putBoolean("expired",getIntent().getBooleanExtra("expired",false));
            previewFragment.setArguments(bundle);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.frameLayout,previewFragment)
                    .commit();
        */
            questionFragment=new SingleQuestionFragment();
            questionFragment.setArguments(bundle);
            questionFragment.setListener(this);
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.frameLayout,questionFragment)
                    .commit();
//        ActivityCompat.requestPermissions(this,
//                    new String[]{Manifest.permission.CAMERA},
//                    111);
        if (!Utility.isDeviceSupportCamera(getApplicationContext())) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! Your device doesn't support camera",
                    Toast.LENGTH_LONG).show();
            // will close the app if the device doesn't have camera
            finish();
        }
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        Uri imageUri = getOutputMediaFileUri();
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
//        startActivityForResult(intent, 100);

    }
//    private Uri getOutputMediaFileUri()
//    {
//        File mediaFile = null;
//        File mediaStorageDir = new File("/sdcard/Android/data/com.b2lmobitech.spottest/"+"Spottestimages");
//        if(!mediaStorageDir.exists())
//        {
//            if(!mediaStorageDir.mkdirs())
//            {
//              return  null;
//            }
//        }
//        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
//                Locale.getDefault()).format(new Date());
//        mediaFile = new File(mediaStorageDir.getPath() + File.separator
//
//                + "IMG_" + System.currentTimeMillis() + ".jpg");//timeStamp
//        try {
//            //mediaFile.getParentFile().mkdirs();
//            mediaFile.createNewFile();
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//
//            return  FileProvider.getUriForFile(getApplicationContext(),
//                    BuildConfig.APPLICATION_ID + ".provider",
//                    mediaFile);//getActivity()
//
////            Log.e("Androdid", "n");
//        } else {
//            return Uri.fromFile(mediaFile);
////            Log.e("Androdid", "below n");
//        }
//        //  uri= Uri.fromFile(mediaFile);
//
//
//    }

    private BroadcastReceiver broadcastReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if(timerText!=null) {
                timerText.setText(intent.getStringExtra("timer"));
            }

            if(intent.getBooleanExtra("submit",false)){
                if(isMock){
                    alertSubmit();
                }else if (questionFragment != null) {
                    questionFragment.submitAnswer();
                } else {
                    previewFragment.submitAnswer();
                }
            }

            if(intent.getBooleanExtra("alert",false)){
                alert(intent.getStringExtra("text"));
            }
        }
    };

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

        if(isMock){
            registerReceiver(broadcastReceiver, new IntentFilter("spottest.timer.mock"));
        }else {
            registerReceiver(broadcastReceiver, new IntentFilter("spottest.timer"));
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
        /*if(CameraRequest) {
            if (questionFragment != null) {
                questionFragment.submitAnswer();
            } else {
                previewFragment.submitAnswer();
            }
        }*/
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        /*if(!CameraRequest) {
            if (questionFragment != null) {
                questionFragment.submitAnswer();
            } else {
                previewFragment.submitAnswer();
            }
        }*/
    }

    private void startTimer(final int maxSeconds){
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                starttime=starttime+1;
                if(starttime<maxSeconds) {
                    handler.postDelayed(this, 1000);
                }
                timerText.setText(getMinitues(starttime));

            }
        }, 1000);
    }

    private String getMinitues(int givenSeconds){

        String time="";
        int minitues=givenSeconds/60;

        if(minitues<10){
            time="0"+minitues;
        }else{
            time=""+minitues;
        }

        int seconds=givenSeconds%60;

        if(seconds<10){
            time=time+":0"+seconds;
        }else{
            time=time+":"+seconds;
        }

        return time;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_questions, menu);
        return true;
    }
    MenuItem submit;
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        submit=menu.findItem(R.id.done);
        submit.setVisible(false);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.done) {
            if (questionFragment != null) {
                questionFragment.submitAnswer();
            } else {
                previewFragment.submitAnswer();
            }

        }
        return super.onOptionsItemSelected(item);
    }

    private void alertSubmit(){}

    private void alert(String string){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setNegativeButton("CLOSE", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.dismiss();
            }
        });
        builder.setMessage(string);
        AlertDialog dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }


    @Override
    public void RequestStarted() {
        CameraRequest=true;
    }

    @Override
    public void RequestFinished() {
        CameraRequest=false;
    }

    @Override
    public void EnableSubmit() {
        submit.setVisible(true);
    }
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        Toast.makeText(this,"onactivityersult_main",Toast.LENGTH_SHORT).show();
////        for (Fragment fragment : getSupportFragmentManager().getFragments()) {
////            fragment.onActivityResult(requestCode, resultCode, data);
//        }

//    }

//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//
//        if (requestCode == 111) {
//            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//
//                Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
//            } else {
//                Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
//            }
//        }
//    }
//@Override
//protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//
//        super.onActivityResult(requestCode, resultCode, data);
//
//}
}
