package app.mar.activities;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.BeepManager;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.CaptureManager;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;

import java.util.List;

import app.mar.game.Game;
import app.mar.game.challenges.Challenge;
import app.mar.game.challenges.QRCodeGeoTreasure;
import app.mar.game.challenges.QRCodeTreasure;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link QRCodeFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link QRCodeFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class QRCodeFragment extends ChallengeFragment  implements
        DecoratedBarcodeView.TorchListener, BarcodeCallback {
    private CaptureManager capture;
    private DecoratedBarcodeView barcodeScannerView;
    private Button switchFlashlightButton;
    private BeepManager beepManager;
    private Game mGame;
    public static final int REQUEST_CODE = 2001;
    private QRCodeTreasure mQr;
    private OnFragmentInteractionListener mListener;

    public QRCodeFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment QRCodeFragment.
     */
    public static QRCodeFragment newInstance() {
        QRCodeFragment fragment = new QRCodeFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
        }
    }

    @Override
    protected void onInitChallenge(Challenge c) {
        if(c instanceof QRCodeTreasure) {
            mQr = (QRCodeTreasure) c;
        }else
        {
            mQr=null;
        }
        if( (c instanceof QRCodeGeoTreasure) )
        {
            getDriver().startLocalisation();
        }

        getDriver().setVisibilityView(R.id.btn_valid, View.INVISIBLE);
    }

    @Override
    protected void onResetUi() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = super.onCreateView(inflater, container, R.layout.fragment_qrcode);
        barcodeScannerView = (DecoratedBarcodeView)v.findViewById(R.id.zxing_barcode_scanner);
        barcodeScannerView.setTorchListener(this);
        beepManager=new BeepManager(getActivity());

        switchFlashlightButton = (Button)v.findViewById(R.id.switch_flashlight);


        if (!hasFlash()) {
            switchFlashlightButton.setVisibility(View.GONE);
        }

        capture = new CaptureManager(getActivity(), barcodeScannerView);
        capture.initializeFromIntent(getActivity().getIntent(), savedInstanceState);

        barcodeScannerView.decodeContinuous(this);
        return v;
    }


    @Override
    public void onStart() {
        super.onStart();
        getDriver().resumeLocalisation();
    }

    @Override
    public void onStop() {
        super.onStop();
        getDriver().pauseLocalisation();
    }

    @Override
    public void onResume() {
        super.onResume();
        capture.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        capture.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        capture.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        capture.onSaveInstanceState(outState);
    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return barcodeScannerView.onKeyDown(keyCode, event) || getActivity().onKeyDown(keyCode, event);
    }

    /**
     * Check if the device's camera has a Flashlight.
     * @return true if there is Flashlight, otherwise false.
     */
    private boolean hasFlash() {
        return getActivity().getApplicationContext().getPackageManager()
                .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    }

    public void switchFlashlight(View view) {
        if ("on".equals(switchFlashlightButton.getText())) {
            barcodeScannerView.setTorchOn();
        } else {
            barcodeScannerView.setTorchOff();
        }
    }

    @Override
    public void onTorchOn() {
        switchFlashlightButton.setText("Off");
    }

    @Override
    public void onTorchOff() {
        switchFlashlightButton.setText("On");
    }

    public void barcodeResult(final BarcodeResult result) {
        beepManager.playBeepSoundAndVibrate();

        Toast.makeText(getActivity(),"Text: '"+result.getText()+"'", Toast.LENGTH_LONG).show();

        if(result.getText().compareTo(mQr.getQRValue())==0)
        {
            barcodeScannerView.pause();
            Activity act = getActivity();
            getDriver().challengeValidate(mChallenge);
        }else
        {
            Toast.makeText(getActivity(), mQr.getBadQRMessage(), Toast.LENGTH_LONG).show();
            barcodeScannerView.decodeContinuous(this);
        }

    }

    @Override
    public void possibleResultPoints(List<ResultPoint> resultPoints) {

    }

    @Override
    public boolean check() {
        return false;
    }


}
